前言
在Spring Cloud微服務開發中使用Feign時需要處理令牌中繼的問題,只有令牌中繼才能在調用鏈中保證用戶認證信息的傳遞,實現將A服務中的用戶認證信息通過Feign隱式傳遞給B服務。今天就來分享一下如何在Feign中實現令牌中繼。
令牌中繼
令牌中繼(Token Relay)是比較正式的說法,說白了就是讓Token令牌在服務間傳遞下去以保證資源服務器能夠正確地對調用方進行資源鑒權??蛻舳送ㄟ^網關攜帶JWT訪問了A服務,A服務對JWT進行了校驗解析,A服務調用B服務時,可能B服務也需要對JWT進行校驗解析。舉個例子,查詢我的訂單以及我訂單的物流信息,訂單服務通過JWT能夠獲得我的userId,如果不中繼令牌需要顯式把userId在傳遞給物流信息服務,甚至有時候下游服務還有權限的問題要處理,所以令牌中繼是非常必要的。
令牌難道不能在Feign自動中繼嗎?
如果我們攜帶Token去訪問A服務,A服務肯定能夠鑒權,但是A服務又通過Feign調用B服務,這時候A的令牌是無法直接傳遞給B服務的。
這里來簡單說下原因,服務間的調用通過Feign接口來進行。在調用方通常我們編寫類似下面的Feign接口:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@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放在請求頭中,偽代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
/** * 需要注入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下面的片段:
1
|
Supplier<Future<T>> futureSupplier = () -> executorService.submit(toRun::get); |
SecurityContextHolder保存信息是默認是通過ThreadLocal實現的,我們都知道這個是不能跨線程的,而Feign的攔截器這時恰恰在子線程中,因此開啟了熔斷功能(circuitBreaker)的Feign無法直接進行令牌中繼。
熔斷組件有過時的Hystrix、Resilience4J、還有阿里的哨兵Sentinel,它們的機制可能有小小的不同。
實現令牌中繼
雖然直接不能實現令牌中繼,但是我從中還是找到了一些信息。在Feign接口代理的處理器FeignCircuitBreakerInvocationHandler中發現了下面的代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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代理類的執行代碼,我們可以看到在執行前:
1
|
final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); |
這里是獲得調用線程中請求的信息,包含了ServletHttpRequest、ServletHttpResponse等信息。緊接著又在lambda代碼中把這些信息又Setter了進去:
1
|
RequestContextHolder.setRequestAttributes(requestAttributes); |
如果這是一個線程中進行的簡直就是吃飽了撐的,事實上Supplier返回值是在另一個線程中執行的。這樣做的目的就是為了跨線程保存一些請求的元數據。
InheritableThreadLocal
RequestContextHolder 是如何做到跨線程了傳遞數據的呢?
1
2
3
4
5
6
7
8
9
|
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把調用方的請求信息帶進了子線程,借助于這個原理就能實現令牌中繼了。
實現令牌中繼
把最開始的Feign攔截器代碼改動了一下就實現了令牌的中繼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
/** * 令牌中繼 */ 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。
總結
微服務令牌中繼是非常重要的,保證了用戶狀態在調用鏈路的傳遞。而且這也是微服務的難點。今天借助于Feign的一些特性和ThreadLocal的特性實現了令牌中繼供大家參考。
到此這篇關于JWT在OpenFeign調用中進行令牌中繼的文章就介紹到這了,更多相關JWT OpenFeign令牌中繼內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://juejin.cn/post/7023246872147918885