<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          Spring Cloud Feign如何實現(xiàn)JWT令牌中繼以傳遞認證信息

          共 4911字,需瀏覽 10分鐘

           ·

          2021-11-04 15:49

          在上一篇實現(xiàn)了Spring Cloud資源服務器的定制化,但是又發(fā)現(xiàn)了一個新的問題,Spring Cloud微服務調用的過程中需要令牌中繼。只有令牌中繼才能在調用鏈中保證用戶認證信息的傳遞。今天就來分享一下如何在Feign中實現(xiàn)令牌中繼。

          令牌中繼

          令牌中繼(Token Relay)是比較正式的說法,說白了就是讓Token令牌在服務間傳遞下去以保證資源服務器能夠正確地對調用方進行鑒權。

          令牌難道不能在Feign自動中繼嗎?

          如果我們攜帶Token去訪問A服務,A服務肯定能夠鑒權,但是A服務又通過Feign調用B服務,這時候A的令牌是無法直接傳遞給B服務的。

          這里來簡單說下原因,服務間的調用通過Feign接口來進行。在調用方通常我們編寫類似下面的Feign接口:

          @FeignClient(name?=?"foo-service",fallback?=?FooClient.Fallback.class)
          public?interface?FooClient?
          {
          ????@GetMapping("/foo/bar")
          ????Rest>?bar();

          ????@Component
          ????class?Fallback?implements?FooClient?{
          ????????@Override
          ????????public?Rest>?bar()?{
          ????????????return?RestBody.fallback();
          ????????}
          ????}
          }

          當我們調用Feign接口后,會通過動態(tài)代理來生成該接口的代理類供我們調用。如果我們不打開熔斷我們可以從Spring Security提供SecurityContext對象中提取到資源服務器的認證對象JwtAuthenticationToken,它包含了JWT令牌然后我們可以通過實現(xiàn)Feign的攔截器接口RequestInterceptor把Token放在請求頭中,偽代碼如下:

          /**
          ?*?需要注入Spring?IoC
          ?**/

          static?class?BearerTokenRequestInterceptor?implements?RequestInterceptor?{
          ????????@Override
          ????????public?void?apply(RequestTemplate?template)?{
          ????????????final?String?authorization?=?HttpHeaders.AUTHORIZATION;
          ????????????Authentication?authentication?=?SecurityContextHolder.getContext().getAuthentication();
          ????????????
          ????????????if?(authentication?instanceof?JwtAuthenticationToken){
          ????????????????JwtAuthenticationToken?jwtAuthenticationToken?=?(JwtAuthenticationToken)?authentication;
          ????????????????String?tokenValue?=?jwtAuthenticationToken.getToken().getTokenValue();
          ????????????????template.header(authorization,"Bearer?"+tokenValue);
          ????????????}
          ????????}
          ????}

          如果我們不開啟熔斷這樣搞問題不大,為了防止調用鏈雪崩服務熔斷基本沒有不打開的。這時候從SecurityContextHolder就無法獲取到Authentication了。因為這時Feign調用是在調用方的調用線程下又開啟了一個子線程中進行的。由于我使用的熔斷組件是Resilience4J,對應的線程源碼在Resilience4JCircuitBreaker中:

          ?Supplier>?futureSupplier?=?()?->?executorService.submit(toRun::get);

          SecurityContextHolder保存信息是默認是通過ThreadLocal實現(xiàn)的,我們都知道這個是不能跨線程的,而Feign的攔截器這時恰恰在子線程中,因此開啟了熔斷功能(circuitBreaker)的Feign無法直接進行令牌中繼

          ?

          熔斷組件有過時的Hystrix、Resilience4J、還有阿里的哨兵Sentinel,它們的機制可能有小小的不同。

          實現(xiàn)令牌中繼

          雖然直接不能實現(xiàn)令牌中繼,但是我從中還是找到了一些信息。在Feign接口代理的處理器FeignCircuitBreakerInvocationHandler中發(fā)現(xiàn)了下面的代碼:

          private?Supplier?asSupplier(final?Method?method,?final?Object[]?args)?{
          ??final?RequestAttributes?requestAttributes?=?RequestContextHolder.getRequestAttributes();
          ??return?()?->?{
          ???try?{
          ????RequestContextHolder.setRequestAttributes(requestAttributes);
          ????return?this.dispatch.get(method).invoke(args);
          ???}
          ???catch?(RuntimeException?throwable)?{
          ????throw?throwable;
          ???}
          ???catch?(Throwable?throwable)?{
          ????throw?new?RuntimeException(throwable);
          ???}
          ???finally?{
          ????RequestContextHolder.resetRequestAttributes();
          ???}
          ??};
          ?}

          這是Feign代理類的執(zhí)行代碼,我們可以看到在執(zhí)行前:

          ??final?RequestAttributes?requestAttributes?=?RequestContextHolder.getRequestAttributes();

          這里是獲得調用線程中請求的信息,包含了ServletHttpRequestServletHttpResponse等信息。緊接著又在lambda代碼中把這些信息又Setter了進去:

          ?RequestContextHolder.setRequestAttributes(requestAttributes);

          如果這是一個線程中進行的簡直就是吃飽了撐的,事實上Supplier返回值是在另一個線程中執(zhí)行的。這樣做的目的就是為了跨線程保存一些請求的元數(shù)據。

          InheritableThreadLocal

          RequestContextHolder?是如何做到跨線程了傳遞數(shù)據的呢?

          public?abstract?class?RequestContextHolder??{
          ?
          ?private?static?final?ThreadLocal?requestAttributesHolder?=
          ???new?NamedThreadLocal<>("Request?attributes");

          ?private?static?final?ThreadLocal?inheritableRequestAttributesHolder?=
          ???new?NamedInheritableThreadLocal<>("Request?context");
          //?省略
          }

          RequestContextHolder?維護了兩個容器,一個是不能跨線程的ThreadLocal,一個是實現(xiàn)了InheritableThreadLocalNamedInheritableThreadLocalInheritableThreadLocal是可以把父線程的數(shù)據傳遞到子線程的,基于這個原理RequestContextHolder把調用方的請求信息帶進了子線程,借助于這個原理就能實現(xiàn)令牌中繼了。

          實現(xiàn)令牌中繼

          把最開始的Feign攔截器代碼改動了一下就實現(xiàn)了令牌的中繼:

          ????/**
          ?????*?令牌中繼
          ?????*/

          ????static?class?BearerTokenRequestInterceptor?implements?RequestInterceptor?{
          ????????private?static?final?Pattern?BEARER_TOKEN_HEADER_PATTERN?=?Pattern.compile("^Bearer?(?[a-zA-Z0-9-._~+/]+=*)$",
          ????????????????Pattern.CASE_INSENSITIVE);

          ????????@Override
          ????????public?void?apply(RequestTemplate?template)?{
          ????????????final?String?authorization?=?HttpHeaders.AUTHORIZATION;
          ????????????ServletRequestAttributes?requestAttributes?=?(ServletRequestAttributes)?RequestContextHolder.getRequestAttributes();
          ????????????if?(Objects.nonNull(requestAttributes))?{
          ????????????????String?authorizationHeader?=?requestAttributes.getRequest().getHeader(HttpHeaders.AUTHORIZATION);
          ????????????????Matcher?matcher?=?BEARER_TOKEN_HEADER_PATTERN.matcher(authorizationHeader);
          ????????????????if?(matcher.matches())?{
          ????????????????????//?清除token頭?避免傳染
          ????????????????????template.header(authorization);
          ????????????????????template.header(authorization,?authorizationHeader);
          ????????????????}
          ????????????}
          ????????}
          ????}

          這樣當你調用FooClient.bar()時,在foo-service中資源服務器(OAuth2 Resource Server)也可以獲得調用方的令牌,進而獲得用戶的信息來處理資源權限和業(yè)務。

          ?

          不要忘記將這個攔截器注入Spring IoC。

          總結

          微服務令牌中繼是非常重要的,保證了用戶狀態(tài)在調用鏈路的傳遞。而且這也是微服務的難點。今天借助于Feign的一些特性和ThreadLocal的特性實現(xiàn)了令牌中繼供大家參考。原創(chuàng)不易,請大家多多點擊再看、點贊、轉發(fā)。


          推薦關注本文作者:碼農小胖哥
          分享高質量編程知識,探討IT人生
          技術干貨,實戰(zhàn)技巧,面試技巧,前沿資訊一個都不能少

          瀏覽 47
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                    <th id="afajh"><progress id="afajh"></progress></th>
                    WwW69免费视频 | 看全色黄大色大片 | 欧美操女人 | 国产一区久久 | 少妇后入在线观看 |