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

本文介绍了如何在SpringSecurity3.2.1与Springboot集成时,自定义处理认证失败和授权失败的异常,包括实现`AuthenticationEntryPoint`和`AccessDeniedHandler`,以及如何在SpringSecurity配置中应用这些自定义处理方法。
摘要由CSDN通过智能技术生成

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();
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值