springboot~security中自定義forbidden和unauthorized返(fan)回(hui)值(zhi)
對于spring-security來說,當你訪問一個受保護資源時,需要檢查你的token,當沒有傳遞,或者傳遞的token有錯誤時,將出現401unauthorized異常;當你傳遞的token是有效的,但解析后并沒有訪問這個資源的權限時,將返回403forbidden的異常,而你通過攔截器@RestControllerAdvice是不能(neng)重寫這兩個異常消(xiao)(xiao)息的,我們下面介紹重寫這兩種消(xiao)(xiao)息的方(fang)法。
兩個接口
- 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": "沒有訪問權限!"
}