天天看點

Spring Cloud Feign如何實作JWT令牌中繼,傳遞認證資訊?令牌中繼實作令牌中繼實作令牌中繼總結

在上一篇實作了 Spring Cloud資源伺服器的定制化 ,但是又發現了一個新的問題,Spring Cloud微服務調用的過程中需要令牌中繼。隻有令牌中繼才能在調用鍊中保證使用者認證資訊的傳遞。今天就來分享一下如何在Feign中實作令牌中繼。

https://blog.didispace.com/spring-cloud-feign-transmit-jwt/#%E4%BB%A4%E7%89%8C%E4%B8%AD%E7%BB%A7 令牌中繼

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

https://blog.didispace.com/spring-cloud-feign-transmit-jwt/#%E4%BB%A4%E7%89%8C%E9%9A%BE%E9%81%93%E4%B8%8D%E8%83%BD%E5%9C%A8Feign%E8%87%AA%E5%8A%A8%E4%B8%AD%E7%BB%A7%E5%90%97%EF%BC%9F 令牌難道不能在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<Map<String, String>> bar();

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

當我們調用Feign接口後,會通過動态代理來生成該接口的代理類供我們調用。如果我們不打開熔斷我們可以從Spring Security提供SecurityContext對象中提取到資源伺服器的認證對象JwtAuthenticationToken,它包含了JWT令牌然後我們可以通過實作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<Future<T>> futureSupplier = () -> executorService.submit(toRun::get);      

SecurityContextHolder儲存資訊是預設是通過ThreadLocal實作的,我們都知道這個是不能跨線程的,而Feign的攔截器這時恰恰在子線程中,是以開啟了熔斷功能(circuitBreaker)的Feign無法直接進行令牌中繼。

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

https://blog.didispace.com/spring-cloud-feign-transmit-jwt/#%E5%AE%9E%E7%8E%B0%E4%BB%A4%E7%89%8C%E4%B8%AD%E7%BB%A7 實作令牌中繼

雖然直接不能實作令牌中繼,但是我從中還是找到了一些資訊。在Feign接口代理的處理器FeignCircuitBreakerInvocationHandler中發現了下面的代碼:

private Supplier<Object> 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代理類的執行代碼,我們可以看到在執行前:

final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();      

這裡是獲得調用線程中請求的資訊,包含了ServletHttpRequest、ServletHttpResponse等資訊。緊接着又在lambda代碼中把這些資訊又Setter了進去:

RequestContextHolder.setRequestAttributes(requestAttributes);      

如果這是一個線程中進行的簡直就是吃飽了撐的,事實上Supplier傳回值是在另一個線程中執行的。這樣做的目的就是為了跨線程儲存一些請求的中繼資料。

https://blog.didispace.com/spring-cloud-feign-transmit-jwt/#InheritableThreadLocal InheritableThreadLocal

RequestContextHolder 是如何做到跨線程了傳遞資料的呢?

public abstract class RequestContextHolder  {

private static final ThreadLocal<RequestAttributes> requestAttributesHolder =
new NamedThreadLocal<>("Request attributes");

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

RequestContextHolder 維護了兩個容器,一個是不能跨線程的ThreadLocal,一個是實作了InheritableThreadLocal的NamedInheritableThreadLocal。InheritableThreadLocal是可以把父線程的資料傳遞到子線程的,基于這個原理RequestContextHolder把調用方的請求資訊帶進了子線程,借助于這個原理就能實作令牌中繼了。

https://blog.didispace.com/spring-cloud-feign-transmit-jwt/#%E5%AE%9E%E7%8E%B0%E4%BB%A4%E7%89%8C%E4%B8%AD%E7%BB%A7-1

把最開始的Feign攔截器代碼改動了一下就實作了令牌的中繼:

/**
* 令牌中繼
*/
static class BearerTokenRequestInterceptor implements RequestInterceptor {
private static final Pattern BEARER_TOKEN_HEADER_PATTERN = Pattern.compile("^Bearer (?<token>[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)也可以獲得調用方的令牌,進而獲得使用者的資訊來處理資源權限和業務。

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

https://blog.didispace.com/spring-cloud-feign-transmit-jwt/#%E6%80%BB%E7%BB%93 總結

微服務令牌中繼是非常重要的,保證了使用者狀态在調用鍊路的傳遞。而且這也是微服務的難點。今天借助于Feign的一些特性和ThreadLocal的特性實作了令牌中繼供大家參考。原創不易,請大家多多點選再看、點贊、轉發。

好了,今天的學習就到這裡!如果您學習過程中如遇困難?可以加入我們超高品質的

Spring技術交流群

,參與交流與讨論,更好的學習與進步!更多

Spring Cloud教程可以點選直達!

,歡迎收藏與轉發支援!