springboot~security中自定义forbidden和unauthorized返回值

springboot~security中自定义forbidden和unauthorized返回值

对于spring-security来说,当你访问一个受保护资源时,需要检查你的token,当没有传递,或者传递的token有错误时,将出现401unauthorized异常;当你传递的token是有效的,但解析后并没有访问这个资源的权限时,将返回403forbidden的异常,而你通过拦截器@RestControllerAdvice是不能重写这两个异常消息的,我们下面介绍重写这两种消息的方法。

两个接口

  • AccessDeniedHandler 实现重写403的消息
  • AuthenticationEntryPoint 实现重写401的消息

代码

  • CustomAccessDeineHandler
public class CustomAccessDeineHandler implements AccessDeniedHandler {

  @Override
  public void handle(HttpServletRequest request, HttpServletResponse response,
                     AccessDeniedException accessDeniedException) throws IOException, ServletException {
    response.setCharacterEncoding("utf-8");
    response.setContentType("application/json;charset=utf-8");
    response.getWriter().print(JSONObject.toJSONString(CommonResult.forbiddenFailure("没有访问权限!")));
  }

}
  • CustomAuthenticationEntryPoint
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

  @Override
  public void commence(HttpServletRequest request, HttpServletResponse response,
                       AuthenticationException authException) throws IOException, ServletException {
    response.setCharacterEncoding("utf-8");
    response.setContentType("application/json;charset=utf-8");
    response.getWriter().print(JSONObject.toJSONString(CommonResult.unauthorizedFailure("需要先认证才能访问!")));
  }

}
  • WebSecurityConfig.configure中添加注入代码
  // 401和403自定义
  http.exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint())
      .accessDeniedHandler(new CustomAccessDeineHandler());
  • 效果
//没有传token,或者token不合法
{
    "code": 401,
    "message": "需要先认证才能访问!"
}
//token中没有权限
{
    "code": 403,
    "message": "没有访问权限!"
}
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » springboot~security中自定义forbidden和unauthorized返回值