SpringCloudAlibaba中Oauth2認證服務(wù)器自定義異常怎么辦

這篇文章將為大家詳細講解有關(guān)SpringCloud Alibaba中Oauth2認證服務(wù)器自定義異常怎么辦,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

按需定制可以根據(jù)自己的需求進行定制,網(wǎng)站建設(shè)、成都網(wǎng)站建設(shè)構(gòu)思過程中功能建設(shè)理應(yīng)排到主要部位公司網(wǎng)站建設(shè)、成都網(wǎng)站建設(shè)的運用實際效果公司網(wǎng)站制作網(wǎng)站建立與制做的實際意義

前言

問題:在使用 Spring Security OAuth3 時如何自定義認證服務(wù)器返回異常。

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

授權(quán)模式錯誤

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

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

密碼錯誤

在認證時故意輸錯 username 或 password 會出現(xiàn)如下異常錯誤:

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

客戶端錯誤

在認證時故意輸錯 client_id 或 client

{   "error": "invalid_client",   "error_description": "Bad client credentials" } 上面的返回結(jié)

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

問題剖析

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

OAuth3Exception異常處理

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

SpringCloud Alibaba中Oauth2認證服務(wù)器自定義異常怎么辦

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

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

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

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

客戶端異常處理

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

SpringCloud Alibaba中Oauth2認證服務(wù)器自定義異常怎么辦

然后跳轉(zhuǎn)到父類的 AbstractOAuth3SecurityExceptionHandler#doHandle()進行處理:

SpringCloud Alibaba中Oauth2認證服務(wù)器自定義異常怎么辦

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

SpringCloud Alibaba中Oauth2認證服務(wù)器自定義異常怎么辦

處理方法

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

解決方案

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

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

OAuth3Exception異常

@Slf4j public class CustomWebResponseExceptionTranslator implements WebResponseExceptionTranslator {      @Override     public ResponseEntity<ResultData<String>> translate(Exception e) throws Exception {         log.error("認證服務(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();         //不支持的認證方式         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;     }  }

然后在認證服務(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()); }

客戶端異常

重寫客戶端認證過濾器,不使用默認的 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) -> {         });     } }

在認證服務(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);     }; }

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

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

測試

授權(quán)模式錯誤

SpringCloud Alibaba中Oauth2認證服務(wù)器自定義異常怎么辦

賬號密碼錯誤

SpringCloud Alibaba中Oauth2認證服務(wù)器自定義異常怎么辦

客戶端錯誤

SpringCloud Alibaba中Oauth2認證服務(wù)器自定義異常怎么辦

關(guān)于“SpringCloud Alibaba中Oauth2認證服務(wù)器自定義異常怎么辦”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

當前題目:SpringCloudAlibaba中Oauth2認證服務(wù)器自定義異常怎么辦
網(wǎng)站網(wǎng)址:http://muchs.cn/article42/gecjec.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供虛擬主機、全網(wǎng)營銷推廣、外貿(mào)網(wǎng)站建設(shè)營銷型網(wǎng)站建設(shè)、手機網(wǎng)站建設(shè)、外貿(mào)建站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站制作