1

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

 2 years ago
source link: https://www.cnblogs.com/lori/p/16066267.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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": "没有访问权限!"
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK