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 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 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,secrunity,spring,数据库,java)