springboot~security中自定義forbidden和unauthorized返回值
對(duì)于spring-security來(lái)說(shuō),當(dāng)你訪問(wèn)一個(gè)受保護(hù)資源時(shí),需要檢查你的token,當(dāng)沒(méi)有傳遞,或者傳遞的token有錯(cuò)誤時(shí),將出現(xiàn)401unauthorized異常;當(dāng)你傳遞的token是有效的,但解析后并沒(méi)有訪問(wèn)這個(gè)資源的權(quán)限時(shí),將返回403forbidden的異常,而你通過(guò)攔截器@RestControllerAdvice是不能重寫這兩個(gè)異常消息的,我們下面介紹重寫這兩種消息的方法。
兩個(gè)接口
- AccessDeniedHandler 實(shí)現(xiàn)重寫403的消息
- AuthenticationEntryPoint 實(shí)現(xiàn)重寫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("沒(méi)有訪問(wèn)權(quán)限!")));
}
}
- 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("需要先認(rèn)證才能訪問(wèn)!")));
}
}
- WebSecurityConfig.configure中添加注入代碼
// 401和403自定義
http.exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint())
.accessDeniedHandler(new CustomAccessDeineHandler());
- 效果
//沒(méi)有傳token,或者token不合法
{
"code": 401,
"message": "需要先認(rèn)證才能訪問(wèn)!"
}
//token中沒(méi)有權(quán)限
{
"code": 403,
"message": "沒(méi)有訪問(wèn)權(quán)限!"
}
浙公網(wǎng)安備 33010602011771號(hào)