溫馨提示×

溫馨提示×

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

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

在使用Spring Security OAuth3時如何自定義認(rèn)證服務(wù)器返回異常

發(fā)布時間:2021-10-19 12:00:05 來源:億速云 閱讀:350 作者:iii 欄目:編程語言

本篇內(nèi)容介紹了“在使用Spring Security OAuth3時如何自定義認(rèn)證服務(wù)器返回異?!钡挠嘘P(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

那么首先我們先以 Password模式為例看看在認(rèn)證時會出現(xiàn)哪些異常情況。

授權(quán)模式錯誤

這里我們故意將授權(quán)模式 password 修改成 password1,認(rèn)證服務(wù)器返回如下所示的異常

{
  "error": "unsupported_grant_type",
  "error_description": "Unsupported grant type: password1"
}
     

密碼錯誤

在認(rèn)證時故意輸錯 usernamepassword 會出現(xiàn)如下異常錯誤:

{
  "error": "invalid_grant",
  "error_description": "Bad credentials"
}
     

客戶端錯誤

在認(rèn)證時故意輸錯 client_idclient_secret

{
  "error": "invalid_client",
  "error_description": "Bad client credentials"
}
     

上面的返回結(jié)果很不友好,而且前端代碼也很難判斷是什么錯誤,所以我們需要對返回的錯誤進行統(tǒng)一的異常處理,讓其返回統(tǒng)一的異常格式。

     

問題剖析

如果只關(guān)注解決方案,可以直接跳轉(zhuǎn)到解決方案模塊!

     

OAuth3Exception異常處理

在Oauth3認(rèn)證服務(wù)器中認(rèn)證邏輯最終調(diào)用的是 TokenEndpoint#postAccessToken()方法,而一旦認(rèn)證出現(xiàn) OAuth3Exception異常則會被 handleException()捕獲到異常。如下圖展示的是當(dāng)出現(xiàn)用戶密碼異常時debug截圖:

在使用Spring Security OAuth3時如何自定義認(rèn)證服務(wù)器返回異常

認(rèn)證服務(wù)器在捕獲到 OAuth3Exception后會調(diào)用 WebResponseExceptionTranslator#translate()方法對異常進行翻譯處理。

默認(rèn)的翻譯處理實現(xiàn)類是 DefaultWebResponseExceptionTranslator,處理完成后會調(diào)用 handleOAuth3Exception()方法將處理后的異常返回給前端,這就是我們之前看到的異常效果。

     
處理方法

熟悉Oauth3套路的同學(xué)應(yīng)該知道了如何處理此類異常,就是「自定義一個異常翻譯類讓其返回我們需要的自定義格式,然后將其注入到認(rèn)證服務(wù)器中?!?/strong>

但是這種處理邏輯只能解決 OAuth3Exception異常,即前言部分中的「授權(quán)模式異?!?/strong>和「賬號密碼類的異?!?/strong>,并不能解決我們客戶端的異常。

     

客戶端異常處理

客戶端認(rèn)證的異常是發(fā)生在過濾器 ClientCredentialsTokenEndpointFilter上,其中有后置添加失敗處理方法,最后把異常交給 OAuth3AuthenticationEntryPoint這個所謂認(rèn)證入口處理。執(zhí)行順序如下所示:在使用Spring Security OAuth3時如何自定義認(rèn)證服務(wù)器返回異常

然后跳轉(zhuǎn)到父類的 AbstractOAuth3SecurityExceptionHandler#doHandle()進行處理:在使用Spring Security OAuth3時如何自定義認(rèn)證服務(wù)器返回異常

最終由 DefaultOAuth3ExceptionRenderer#handleHttpEntityResponse()方法將異常輸出給客戶端在使用Spring Security OAuth3時如何自定義認(rèn)證服務(wù)器返回異常

     
處理方法

通過上面的分析我們得知客戶端的認(rèn)證失敗異常是過濾器 ClientCredentialsTokenEndpointFilter轉(zhuǎn)交給 OAuth3AuthenticationEntryPoint得到響應(yīng)結(jié)果的,既然這樣我們就可以重寫 ClientCredentialsTokenEndpointFilter然后使用自定義的 AuthenticationEntryPoint替換原生的 OAuth3AuthenticationEntryPoint,在自定義 AuthenticationEntryPoint處理得到我們想要的異常數(shù)據(jù)。

     

解決方案

為了解決上面這些異常,我們首先需要編寫不同異常的錯誤代碼:ReturnCode.java

CLIENT_AUTHENTICATION_FAILED(1001,"客戶端認(rèn)證失敗"),
USERNAME_OR_PASSWORD_ERROR(1002,"用戶名或密碼錯誤"),
UNSUPPORTED_GRANT_TYPE(1003, "不支持的認(rèn)證模式");
           

OAuth3Exception異常

如上所說我們編寫一個自定義異常翻譯類 CustomWebResponseExceptionTranslator

@Slf4j
public class CustomWebResponseExceptionTranslator implements WebResponseExceptionTranslator {

    @Override
    public ResponseEntity<ResultData<String>> translate(Exception e) throws Exception {
        log.error("認(rèn)證服務(wù)器異常",e);

        ResultData<String> response = resolveException(e);

        return new ResponseEntity<>(response, HttpStatus.valueOf(response.getHttpStatus()));
    }

    /**
     * 構(gòu)建返回異常
     * @param e exception
     * @return
     */
    private ResultData<String> resolveException(Exception e) {
        // 初始值 500
        ReturnCode returnCode = ReturnCode.RC500;
        int httpStatus = HttpStatus.UNAUTHORIZED.value();
        //不支持的認(rèn)證方式
        if(e instanceof UnsupportedGrantTypeException){
            returnCode = ReturnCode.UNSUPPORTED_GRANT_TYPE;
        //用戶名或密碼異常
        }else if(e instanceof InvalidGrantException){
            returnCode = ReturnCode.USERNAME_OR_PASSWORD_ERROR;
        }

        ResultData<String> failResponse = ResultData.fail(returnCode.getCode(), returnCode.getMessage());
        failResponse.setHttpStatus(httpStatus);

        return failResponse;
    }

}
     

然后在認(rèn)證服務(wù)器配置類中注入自定義異常翻譯類

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    //如果需要使用refresh_token模式則需要注入userDetailService
    endpoints
            .authenticationManager(this.authenticationManager)
            .userDetailsService(userDetailService)
//                注入tokenGranter
            .tokenGranter(tokenGranter);
            //注入自定義的tokenservice,如果不使用自定義的tokenService那么就需要將tokenServce里的配置移到這里
//                .tokenServices(tokenServices());
    // 自定義異常轉(zhuǎn)換類
    endpoints.exceptionTranslator(new CustomWebResponseExceptionTranslator());
}
           

客戶端異常

重寫客戶端認(rèn)證過濾器,不使用默認(rèn)的 OAuth3AuthenticationEntryPoint處理異常

public class CustomClientCredentialsTokenEndpointFilter extends ClientCredentialsTokenEndpointFilter {

    private final AuthorizationServerSecurityConfigurer configurer;

    private AuthenticationEntryPoint authenticationEntryPoint;

    public CustomClientCredentialsTokenEndpointFilter(AuthorizationServerSecurityConfigurer configurer) {
        this.configurer = configurer;
    }

    @Override
    public void setAuthenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint) {
        super.setAuthenticationEntryPoint(null);
        this.authenticationEntryPoint = authenticationEntryPoint;
    }

    @Override
    protected AuthenticationManager getAuthenticationManager() {
        return configurer.and().getSharedObject(AuthenticationManager.class);
    }

    @Override
    public void afterPropertiesSet() {
        setAuthenticationFailureHandler((request, response, e) -> authenticationEntryPoint.commence(request, response, e));
        setAuthenticationSuccessHandler((request, response, authentication) -> {
        });
    }
}
     

在認(rèn)證服務(wù)器注入異常處理邏輯,自定義異常返回結(jié)果。(代碼位于 AuthorizationServerConfig

@Bean
public AuthenticationEntryPoint authenticationEntryPoint() {
    return (request, response, e) -> {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        ResultData<String> resultData = ResultData.fail(ReturnCode.CLIENT_AUTHENTICATION_FAILED.getCode(), ReturnCode.CLIENT_AUTHENTICATION_FAILED.getMessage());
        WebUtils.writeJson(response,resultData);
    };
}
     

修改認(rèn)證服務(wù)器配置,注入自定義過濾器

@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
 CustomClientCredentialsTokenEndpointFilter endpointFilter = new CustomClientCredentialsTokenEndpointFilter(security);
 endpointFilter.afterPropertiesSet();
 endpointFilter.setAuthenticationEntryPoint(authenticationEntryPoint());
 security.addTokenEndpointAuthenticationFilter(endpointFilter);

 security
   .authenticationEntryPoint(authenticationEntryPoint())
     /* .allowFormAuthenticationForClients()*/ //如果使用表單認(rèn)證則需要加上
   .tokenKeyAccess("permitAll()")
   .checkTokenAccess("isAuthenticated()");
}
     

此時需要刪除 allowFormAuthenticationForClients()配置,否則自定義的過濾器不生效,至于為什么不生效大家看看源碼就知道了。

     

測試

  • 授權(quán)模式錯誤在使用Spring Security OAuth3時如何自定義認(rèn)證服務(wù)器返回異常

  • 賬號密碼錯誤在使用Spring Security OAuth3時如何自定義認(rèn)證服務(wù)器返回異常

  • 客戶端錯誤在使用Spring Security OAuth3時如何自定義認(rèn)證服務(wù)器返回異常


“在使用Spring Security OAuth3時如何自定義認(rèn)證服務(wù)器返回異?!钡膬?nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

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

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

AI