security
创建核心配置文件
@EnableWebSecurity
public class SeurityConfig extends WebSecurityConfigurerAdapter{}
改写方法
/**
* 认证
* 在内存中创建了一个用户
*
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("name")
.password(passwordEncoder.encode("123"))
.roles("ADMIN");//添加角色
}
添加密码加密器
/**
* 给容器加一个密码加密器
*
* @return
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
密码加密
/**
* 对一同个字符串进行加密三次 三次得出的结果是不一样的
* 只要是用同一个加密器加密的 解密也是一样的
* @param args
*/
public static void main(String[] args) {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//加密
System.out.println(bCryptPasswordEncoder.encode("123"));
System.out.println(bCryptPasswordEncoder.encode("123"));
System.out.println(bCryptPasswordEncoder.encode("123"));
//解密
bCryptPasswordEncoder.matches("123","$2a$10$rvN6duVInXYxtuoI.eH53uSOSpgb/mkLVOUQCEfHidHoUnZjxbAf6"));
}
获取当前用户的信息
/**
* 获取当前用户
*
* @param principal
* @return
*/
@GetMapping("getUserInfo")
private String getUserInfo(Principal principal) {
System.out.println(principal);
return "";
}
/**
* 获取当前用户
* <p>
* 当用户登录完之后 会把用户的消息 放到
* SecurityContextHolder 基于session方式的认证
*
* @return
*/
@GetMapping("getUserInfo2")
private Authentication getUserInfo2() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication;
}
登录失败的处理器
/**
* 登录失败的处理器
*
* @return
*/
@Bean
public AuthenticationFailureHandler authenticationFailureHandler() {
return (rquset, response, exception) -> {
response.setContentType("application/json;charset=utf-8");
PrintWriter pw = response.getWriter();
HashMap<String, Object> map = new HashMap<>(4);
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", "登陆失败!");
}
pw.write(new ObjectMapper().writeValueAsString(map));
pw.flush();
pw.close();
};
}
访问接口被拒绝的处理器
/**
* 请求被拒绝的处理器
*
* @return
*/
@Bean
public AccessDeniedHandler accessDeniedHandler() {
return (request, response, accessDeniedException) -> {
response.setContentType("application/json;charset=utf-8");
HashMap<String, Object> map = new HashMap<>(4);
map.put("code", 403);
map.put("msg", "你没有权限");
PrintWriter pw = response.getWriter();
pw.write(new ObjectMapper().writeValueAsString(map));
pw.flush();
pw.close();
};
}