1. 程式人生 > 其它 >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": "沒有訪問許可權!"
}