Spring-Security

Spring Security 是一个能够为基于 Spring 的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在 Spring 应用上下文中配置的 Bean,充分利用了SpringIoC,DI(控制反转 Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。

获取当前登录用户的信息(

/**
* 获取当前用户信息,直接在参数中注入 Principal 对象
* 此对象是登录后自动写入 UsernamePasswordAuthenticationToken 类中
*
* @param principal
* @return
*/
@GetMapping("userInfo")
public Principal getUserInfo(Principal principal) {
return principal;
}
/**
* SecurityContextHolder.getContext()获取安全上下文对象
* 就是那个保存在 ThreadLocal 里面的安全上下文对象
* 总是不为 null(如果不存在,则创建一个 authentication 属性为 null 的 empty 安全上下文对象)
* 获取当前认证了的 principal(当事人),或者 request token (令牌)
* 如果没有认证,会是 null,该例子是认证之后的情况
*/
@GetMapping("userInfo2")
public Object getUserInfo2() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();return authentication;
}

两种方式)

登录成功或者失败都返回 JSON,我们需要自定义处理器

/**
* 登录成功的处理器
*/
@Configuration
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse
response, Authentication authentication) throws IOException {
response.setContentType("application/json;charset=utf-8");
PrintWriter pw = response.getWriter();
Map<String, Object> map = new HashMap<>();
map.put("code", 200);
// 将用户信息放进去
map.put("msg", authentication.getPrincipal());
pw.write(new ObjectMapper().writeValueAsString(map));
pw.flush();
pw.close();
}

登录失败返回 json 的处理器

@Configuration
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse
response, AuthenticationException exception) throws IOException, ServletException {
response.setContentType("application/json;charset=utf-8");
PrintWriter pw = response.getWriter();
Map<String, Object> map = new HashMap<>();
map.put("code", 401);
if (exception instanceof LockedException) {
map.put("msg", "账户被锁定,登陆失败!");
} else if (exception instanceof BadCredentialsException) {
map.put("msg", "账户或者密码错误,登陆失败!");
} else if (exception instanceof DisabledException) {
map.put("msg", "账户被禁用,登陆失败!");
} else if (exception instanceof AccountExpiredException) {
map.put("msg", "账户已过期,登陆失败!");
} else if (exception instanceof CredentialsExpiredException) {
map.put("msg", "密码已过期,登陆失败!");
} else {
map.put("msg", "登陆失败!");
}
System.out.println(exception.getClass().getSimpleName());
pw.write(new ObjectMapper().writeValueAsString(map));
pw.flush();
pw.close();
}
}

### Spring Boot Starter SecuritySpring Security BOM 的区别 #### 功能定位差异 `spring-boot-starter-security` 是一个启动器,旨在简化安全模块集成到基于 Spring Boot 的应用程序中的过程。它自动配置了许多常见的安全设置并提供了默认的安全机制[^1]。 相比之下,`spring-security-bom` 并不是一个具体的库或组件实现者;相反,这是一个 Bill of Materials (BOM),用于管理依赖版本的一致性和兼容性。通过引入 `spring-security-bom` 到项目中,可以确保所有来自 Spring Security 生态系统的依赖项都使用相同且经过测试验证过的版本组合[^2]。 #### 使用场景不同 当开发者希望快速启用基本安全性功能而无需手动调整太多细节时,通常会选择 `spring-boot-starter-security` 。这个 starter 已经包含了大多数开发人员所需的核心类和特性,并能与 Spring Boot 自动化配置无缝协作[^3]。 另一方面,如果团队更关注于整个项目的依赖管理和一致性,则可能会考虑加入 `spring-security-bom` 来控制所使用的各个子项目的具体版本号。这对于大型企业级应用尤其重要,在这些环境中保持一致性的依赖关系对于维护稳定至关重要[^4]。 ```xml <!-- 引入 spring-boot-starter-security --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- 或者引入 spring-security-bom --> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-bom</artifactId> <version>${spring-security.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值