SpringSecurity(三): Springboot 3.2.1 整合 SpringSecurity自定义异常处理

SpringSecurity(三): Springboot 3.2.1 整合 SpringSecurity自定义异常处理

为什么会有异常?

springsecurity需要完成用户的认证和授权,必然会出现认证失败授权失败,抛出对应的异常

security 默认是如何解决的?

1.使用默认登录页面时,跳转至登陆页面

2.不使用默认登陆页面时,报错(不可见)

? security提供了针对认证失败授权失败各自提供了一个处理异常的接口

? 1.认证失败:AuthticationEnterPoint

? 2.授权失败:AccessDiHandler

问题:异常不可见,无法直接使用出现的异常

自定义扩展异常处理办法

1.自定义认证失败和授权失败的处理方案

//授权失败处理
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        String message = accessDeniedException.getMessage();
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(BaseResult.error(message));
    }
}
//认证失败处理
@Component
public class AuthenticationEnterPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        String message = authException.getMessage();
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(BaseResult.error(message));
    }
}

2.配置进入security

@Autowired
private AuthenticationEnterPointImpl authenticationEnterPoint;

@Autowired
private AccessDeniedHandlerImpl accessDeniedHandler;

//2.配置springsecurity的放行路径等信息
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
    http.authorizeHttpRequests(
        auth -> auth.requestMatchers(HttpMethod.POST,"/shopUser/login").permitAll()
        .anyRequest().authenticated()
    );

    http.csrf(csrf -> csrf.disable());

    http.addFilterBefore(securityTokenFilter, UsernamePasswordAuthenticationFilter.class);

    //配置自定义的异常处理类
    http.exceptionHandling()
        //认证失败
        .authenticationEntryPoint(authenticationEnterPoint)
        //授权失败
        .accessDeniedHandler(accessDeniedHandler);

    return http.build();
}