SpringSecurity对认证或授权失败的封装

SpringSecurity中,如果在认证或授权过程发生了异常,会分别将错误封装成AuthenticationExceptionAccessDeniedException,并且会分别调用AuthenticationEntryPointAccessDeniedHandler接口对象的方法来处理,我们可以用已经实现的类也可以自己实现该接口自定义错误处理:

@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        ResponseResult result = new ResponseResult(HttpStatus.FORBIDDEN.value(),"您的权限不足");
        String json = JSON.toJSONString(result);
        //处理异常
        WebUtils.renderString(response,json);
    }
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        ResponseResult result = new ResponseResult(HttpStatus.UNAUTHORIZED.value(),"用户认证失败请查询登录");
        String json = JSON.toJSONString(result);
        //处理异常
        WebUtils.renderString(response,json);
    }
}


实现之后需要在SpringSecurity配置类中配置:

 protected void configure(HttpSecurity http) throws Exception {
        //配置异常处理器
        http.exceptionHandling()
            //配置认证失败处理器
            .authenticationEntryPoint(authenticationEntryPoint)
            .accessDeniedHandler(accessDeniedHandler);
}

版权声明:本文为MarconiYe原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。