溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

基于spring-security出現(xiàn)401 403錯(cuò)誤自定義處理的示例分析

發(fā)布時(shí)間:2021-07-27 14:25:51 來源:億速云 閱讀:160 作者:小新 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)基于spring-security出現(xiàn)401 403錯(cuò)誤自定義處理的示例分析,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

spring-security 401 403錯(cuò)誤自定義處理

為了返回給前端統(tǒng)一的數(shù)據(jù)格式,

一般所有的數(shù)據(jù)都會(huì)以類似下面的方式返回:

public class APIResultDto<T> {
    /**
     * 狀態(tài)碼:-1代表成功,具體參考APIErrorCode類
     */
    private int er;
 
    /**
     * 狀態(tài)描述,可以自行設(shè)置或使用APIErrorCode類中默認(rèn)描述
     */
    private String erMessage;
 
    /**
     * 實(shí)際返回實(shí)體,isSuccess()返回true時(shí)該字段有效
     */
    private T items;
}

但是一些框架,比如本文要說的spring-security是不按照我們自定義規(guī)范處理的,幸運(yùn)的是spring-security框架給了我們可以定制化的地方,只需繼承

ResourceServerConfigurerAdapter

重寫

public void configure(ResourceServerSecurityConfigurer resources) throws Exception

方法即可,在里面添加自定義的針對(duì)授權(quán)時(shí)返回的401以及403錯(cuò)誤碼,

具體如下:

@Autowired
    private AccessDeniedHandler accessDeniedHandler;
    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;
 
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.authenticationEntryPoint(authenticationEntryPoint);
        resources.accessDeniedHandler(accessDeniedHandler);
    }

里面涉及到的AccessDeniedHandler以及AuthenticationEntryPoint

如下所示:

@Component
public class CustomizedAuthenticationEntryPoint implements AuthenticationEntryPoint {
 
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        
         //按照系統(tǒng)自定義結(jié)構(gòu)返回授權(quán)失敗
response.getWriter().write(JSON.toJSONString(APIResultDto.failed(APIErrorCode.AUTH_FAILED)));
    }
}
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
 
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        
          //按照系統(tǒng)自定義結(jié)構(gòu)返回授權(quán)失敗
 response.getWriter().write(JSON.toJSONString(APIResultDto.failed(APIErrorCode.AUTH_FAILED)));
    }
}

關(guān)于狀態(tài)碼401與403區(qū)別

401 表示用戶沒有權(quán)限(令牌,用戶名,密碼錯(cuò)誤)

403 表示用戶有權(quán)限,只是訪問是被禁止的(可以理解為,用戶有權(quán)限,但是某些目錄禁止訪問)

關(guān)于“基于spring-security出現(xiàn)401 403錯(cuò)誤自定義處理的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI