其他分享
首页 > 其他分享> > springboot~security中自定义forbidden和unauthorized返回值

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

作者:互联网

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

两个接口

代码

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

}
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("需要先认证才能访问!")));
  }

}
  // 401和403自定义
  http.exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint())
      .accessDeniedHandler(new CustomAccessDeineHandler());
//没有传token,或者token不合法
{
    "code": 401,
    "message": "需要先认证才能访问!"
}
//token中没有权限
{
    "code": 403,
    "message": "没有访问权限!"
}

标签:utf,springboot,unauthorized,response,访问,token,重写,public,自定义
来源: https://www.cnblogs.com/lori/p/16066267.html