SpringSecurity实现自定义登录接口
1、配置类 ConfigClazz(SpringSecuriey的)
@Resource
private DIYUsernamePasswordAuthenticationFilter diyUsernamePasswordAuthenticationFilter;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests(
authorize -> authorize
.requestMatchers("/user/**","/").hasRole("user")
.requestMatchers("/manager/**").hasRole("manager")
.requestMatchers("/login/**").permitAll()
.anyRequest()
.authenticated()
);
http.formLogin(AbstractHttpConfigurer::disable);
http.logout(logout ->{
logout
.logoutUrl("/goOut").permitAll()
.logoutSuccessHandler((HttpServletRequest request, HttpServletResponse response, Authentication authentication)->{
Map<String, String[]> parameterMap = request.getParameterMap();
if(!parameterMap.isEmpty() && parameterMap.get("TowLogin")[0].equals("true")){
String json = JSON.toJSONString(Code.NOTowLogin);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(json);
} else {
String json = JSON.toJSONString(Code.SuccessLogout);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(json);
}
});
});
http.addFilterAfter(diyUsernamePasswordAuthenticationFilter, LogoutFilter.class);
http.exceptionHandling(exception ->{
exception.authenticationEntryPoint((HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)->{
String json = JSON.toJSONString(Code.NoLogin);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(json);
});
exception.accessDeniedHandler((HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException)->{
String json = JSON.toJSONString(Code.Forbidden);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(json