0
点赞
收藏
分享

微信扫一扫

SpringSecurity异常处理器

原理

在SpringSecurity中,在认证或者授权的过程中出现的异常会被ExceptionTranslationFilter捕获到,在ExceptionTranslationFilter中会去判断这异常是认证失败还是授权失败产生的:

  • 认证过程中出现的异常,会被封装成AuthenticationException,SpringSecurity会调用AuthenticationEntryPoint对象的方法处理这个异常
  • 授权过程中出现的异常,会被封装成AccessDeniedException,SpringSecurity会调用AccessDeniedHandler对象的方法处理这个异常 所以,自定义异常处理,只需要自定义AuthenticationEntryPoint和AccessDeniedHanler,然后在SpringSecurity中进行配置即可。

示例

第一步:自定义认证失败处理器

/**
 * 认证失败处理器
 *
 * @author hc
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        String message = authException.getMessage();
        if (message == null){
            message = "您的权限不足";
        }
        String json = "{\"code\":\"401\",\"msg\":"+ message +"}";
        response.getWriter().write(json);
    }

}

第二步:自定义授权失败处理器

/**
 * 授权失败处理器
 *
 * @author hc
 */
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        String message = accessDeniedException.getMessage();
        if (message == null){
            message = "您的权限不足";
        }
        String json = "{\"code\":\"403\",\"msg\":"+ message +"}";
        response.getWriter().write(json);
    }
}


### 第三步:在SpringSecurity配置文件中配置:
```java
@Resource
private AuthenticationEntryPointImpl authenticationEntryPoint;
@Resource
private AccessDeniedHandlerImpl accessDeniedHandler;

@Override
protected void configure(HttpSecurity http) throws Exception {
    ……
    //处理异常处理器
    http.exceptionHandling()
            .authenticationEntryPoint(authenticationEntryPoint) //认证失败处理器
            .accessDeniedHandler(accessDeniedHandler) //授权失败处理器
    ;
}

第四步:测试。

举报

相关推荐

0 条评论