對于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": "沒有訪問權限!"
}
作者:倉儲大叔,張占嶺,
榮譽:微軟MVP
QQ:853066980
支付寶掃一掃,為大叔打賞!

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/451218.html
標籤:Java
下一篇:Nacos 啟動報錯 Unable to start web server……Unable to start embedded Tomcat
