public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
// 动态认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(password());
}
// 加密方式
@Bean
PasswordEncoder password() {
return new BCryptPasswordEncoder();
}
private final ObjectMapper objectMapper;
private Filter restAuthenticationFilter() throws Exception {
RestAuthenticationFilter filter = new RestAuthenticationFilter(objectMapper);
filter.setAuthenticationSuccessHandler(getAuthenticationSuccessHandler());
filter.setAuthenticationFailureHandler(getAuthenticationFailureHandler());
filter.setAuthenticationManager(authenticationManager());
// 过滤器入口
filter.setFilterProcessesUrl("/authorize/login");
return filter;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// 使用token 关闭csrf
.csrf().disable()
// 跨域配置
.cors().configurationSource(corsConfigurationSource());
http.logout().logoutUrl("/logout");
http.exceptionHandling().accessDeniedPage("/403.html");
http.authorizeRequests(req -> req
// 不需要认证
.antMatchers("/test", "/file/**", "/**/swagger/**",
"/user/**", "/agencies/**", "/zoneSet/**", "/plateSet/**", "/precinctsSet/**", "/intentManagement/**", "/contract/**"
).permitAll()
// 需要ROLE_ADMIN权限
//.antMatchers("/admin/**").hasRole("ADMIN")
// 需要ROLE_USER权限
//.antMatchers("/user/**").hasRole("USER")
// 其他需要认证
.anyRequest().authenticated())
.addFilterAt(restAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.formLogin(form -> form.loginProcessingUrl("/login").permitAll()
// 登录成功后的处理
.successHandler(getAuthenticationSuccessHandler())
// 登录失败后的处理
.failureHandler(getAuthenticationFailureHandler())
.permitAll())
.httpBasic(Customizer.withDefaults())
.csrf(csrf -> csrf.disable())
.logout(logout -> logout.logoutUrl("/logout")
// 退出登录成功后的处理
.logoutSuccessHandler(getLogoutSuccessHandler()));
}
// 登录成功后的处理
private AuthenticationSuccessHandler getAuthenticationSuccessHandler() {
return (req, res, auth) -> {
res.setStatus(HttpStatus.OK.value());
res.getWriter().println();
log.debug("认证成功!");
// 响应给前端
Map<Object, Object> map = new HashMap<>();
map.put("code",200);
map.put("msg","login success");
map.put("data","true");
String jsonMap = new ObjectMapper().writeValueAsString(map);
res.setContentType("application/json;charset=UTF-8");
res.getWriter().println(jsonMap);
};
}
// 登录失败后的处理
private AuthenticationFailureHandler getAuthenticationFailureHandler() {
return (req, res, exp) -> {
ObjectMapper objectMapper = new ObjectMapper();
res.setStatus(HttpStatus.UNAUTHORIZED.value());
res.setContentType(MediaType.APPLICATION_JSON_VALUE);
res.setCharacterEncoding("UTF-8");
res.getWriter().println(objectMapper.writeValueAsString(exp.getMessage()));
log.debug("认证失败!");
Map<Object, Object> map = new HashMap<>();
map.put("code",201);
map.put("msg","login fail");
map.put("data","false");
String jsonMap = new ObjectMapper().writeValueAsString(map);
res.setContentType("application/json;charset=UTF-8");
res.getWriter().println(jsonMap);
};
}
// 退出登录成功后的处理
private LogoutSuccessHandler getLogoutSuccessHandler() {
return (req, resp, auth) -> {
ObjectMapper objectMapper = new ObjectMapper();
resp.setStatus(HttpStatus.OK.value());
resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
// resp.setCharacterEncoding("UTF-8");
// resp.getWriter().println(objectMapper.writeValueAsString(auth));
log.debug("退出登录成功!");
Map<Object, Object> map = new HashMap<>();
map.put("code",200);
map.put("msg","logout success");
map.put("data","true");
String jsonMap = new ObjectMapper().writeValueAsString(map);
resp.setContentType("application/json;charset=UTF-8");
resp.getWriter().println(jsonMap);
};
}
// 解决跨域
private CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
source.registerCorsConfiguration("/**", corsConfiguration);
return source;
}
}