SpringCloud Alibaba實戰二十六 - Oauth2認證服務器自定義異常

前言

今天內容主要是解決一位粉絲提的問題:在使用 Spring Security OAuth2 時如何自定義認證服務器返回異常。


那麼首先我們先以 Password模式爲例看看在認證時會出現哪些異常情況。

授權模式錯誤

這裏我們故意將授權模式 password 修改成 password1,認證服務器返回如下所示的異常

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

密碼錯誤

在認證時故意輸錯 usernamepassword 會出現如下異常錯誤:

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

客戶端錯誤

在認證時故意輸錯 client_idclient_secret

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

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

問題剖析

如果只關注解決方案,可以直接跳轉到解決方案模塊!

OAuth2Exception異常處理

在Oauth2認證服務器中認證邏輯最終調用的是 TokenEndpoint#postAccessToken()方法,而一旦認證出現 OAuth2Exception異常則會被 handleException()捕獲到異常。如下圖展示的是當出現用戶密碼異常時debug截圖:

認證服務器在捕獲到 OAuth2Exception後會調用 WebResponseExceptionTranslator#translate()方法對異常進行翻譯處理。

默認的翻譯處理實現類是 DefaultWebResponseExceptionTranslator,處理完成後會調用 handleOAuth2Exception()方法將處理後的異常返回給前端,這就是我們之前看到的異常效果。

處理方法

熟悉Oauth2套路的同學應該知道了如何處理此類異常,就是「自定義一個異常翻譯類讓其返回我們需要的自定義格式,然後將其注入到認證服務器中。」

但是這種處理邏輯只能解決 OAuth2Exception異常,即前言部分中的「授權模式異常」「賬號密碼類的異常」,並不能解決我們客戶端的異常。

客戶端異常處理

客戶端認證的異常是發生在過濾器 ClientCredentialsTokenEndpointFilter上,其中有後置添加失敗處理方法,最後把異常交給 OAuth2AuthenticationEntryPoint這個所謂認證入口處理。執行順序如下所示:

然後跳轉到父類的 AbstractOAuth2SecurityExceptionHandler#doHandle()進行處理:

最終由 DefaultOAuth2ExceptionRenderer#handleHttpEntityResponse()方法將異常輸出給客戶端

處理方法

通過上面的分析我們得知客戶端的認證失敗異常是過濾器 ClientCredentialsTokenEndpointFilter轉交給 OAuth2AuthenticationEntryPoint得到響應結果的,既然這樣我們就可以重寫 ClientCredentialsTokenEndpointFilter然後使用自定義的 AuthenticationEntryPoint替換原生的 OAuth2AuthenticationEntryPoint,在自定義 AuthenticationEntryPoint處理得到我們想要的異常數據。

解決方案

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

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

OAuth2Exception異常

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

@Slf4j
public class CustomWebResponseExceptionTranslator implements WebResponseExceptionTranslator {

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

        ResultData<String> response = resolveException(e);

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

    /**
     * 構建返回異常
     * @param e exception
     * @return
     */
    private ResultData<String> resolveException(Exception e) {
        // 初始值 500
        ReturnCode returnCode = ReturnCode.RC500;
        int httpStatus = HttpStatus.UNAUTHORIZED.value();
        //不支持的認證方式
        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;
    }

}

然後在認證服務器配置類中注入自定義異常翻譯類

@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());
    // 自定義異常轉換類
    endpoints.exceptionTranslator(new CustomWebResponseExceptionTranslator());
}

客戶端異常

重寫客戶端認證過濾器,不使用默認的 OAuth2AuthenticationEntryPoint處理異常

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) -> {
        });
    }
}

在認證服務器注入異常處理邏輯,自定義異常返回結果。(代碼位於 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);
    };
}

修改認證服務器配置,注入自定義過濾器

@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()*/ //如果使用表單認證則需要加上
   .tokenKeyAccess("permitAll()")
   .checkTokenAccess("isAuthenticated()");
}

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

測試

  • 授權模式錯誤

  • 賬號密碼錯誤

  • 客戶端錯誤



以上,希望對你有所幫助!



End




乾貨分享



這裏爲大家準備了一份小小的禮物,關注公衆號,輸入如下代碼,即可獲得百度網盤地址,無套路領取!

001:《程序員必讀書籍》
002:《從無到有搭建中小型互聯網公司後臺服務架構與運維架構》
003:《互聯網企業高併發解決方案》
004:《互聯網架構教學視頻》
006:《SpringBoot實現點餐系統》
007:《SpringSecurity實戰視頻》
008:《Hadoop實戰教學視頻》
009:《騰訊2019Techo開發者大會PPT》

010: 微信交流羣






近期熱文top



1、關於JWT Token 自動續期的解決方案

2、SpringBoot開發祕籍-事件異步處理

3、架構師之路-服務器硬件掃盲

4、基於Prometheus和Grafana的監控平臺 - 環境搭建

5、RocketMQ進階 - 事務消息



我就知道你“在看”





本文分享自微信公衆號 - JAVA日知錄(javadaily)。
如有侵權,請聯繫 [email protected] 刪除。
本文參與“OSC源創計劃”,歡迎正在閱讀的你也加入,一起分享。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章