前言
在Spring Cloud微服務(wù)開發(fā)中使用Feign時(shí)需要處理令牌中繼的問題,只有令牌中繼才能在調(diào)用鏈中保證用戶認(rèn)證信息的傳遞,實(shí)現(xiàn)將A服務(wù)中的用戶認(rèn)證信息通過Feign隱式傳遞給B服務(wù)。今天就來分享一下如何在Feign中實(shí)現(xiàn)令牌中繼。
令牌中繼
令牌中繼(Token Relay)是比較正式的說法,說白了就是讓Token令牌在服務(wù)間傳遞下去以保證資源服務(wù)器能夠正確地對(duì)調(diào)用方進(jìn)行資源鑒權(quán)??蛻舳送ㄟ^網(wǎng)關(guān)攜帶JWT訪問了A服務(wù),A服務(wù)對(duì)JWT進(jìn)行了校驗(yàn)解析,A服務(wù)調(diào)用B服務(wù)時(shí),可能B服務(wù)也需要對(duì)JWT進(jìn)行校驗(yàn)解析。舉個(gè)例子,查詢我的訂單以及我訂單的物流信息,訂單服務(wù)通過JWT能夠獲得我的userId,如果不中繼令牌需要顯式把userId在傳遞給物流信息服務(wù),甚至有時(shí)候下游服務(wù)還有權(quán)限的問題要處理,所以令牌中繼是非常必要的。
令牌難道不能在Feign自動(dòng)中繼嗎?
如果我們攜帶Token去訪問A服務(wù),A服務(wù)肯定能夠鑒權(quán),但是A服務(wù)又通過Feign調(diào)用B服務(wù),這時(shí)候A的令牌是無法直接傳遞給B服務(wù)的。
這里來簡(jiǎn)單說下原因,服務(wù)間的調(diào)用通過Feign接口來進(jìn)行。在調(diào)用方通常我們編寫類似下面的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(); } } } |
當(dāng)我們調(diào)用Feign接口后,會(huì)通過動(dòng)態(tài)代理來生成該接口的代理類供我們調(diào)用。如果我們不打開熔斷我們可以從Spring Security提供SecurityContext對(duì)象中提取到資源服務(wù)器的認(rèn)證對(duì)象JwtAuthenticationToken,它包含了JWT令牌然后我們可以通過實(shí)現(xiàn)Feign的攔截器接口RequestInterceptor把Token放在請(qǐng)求頭中,偽代碼如下:
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); } } } |
如果我們不開啟熔斷這樣搞問題不大,為了防止調(diào)用鏈雪崩服務(wù)熔斷基本沒有不打開的。這時(shí)候從SecurityContextHolder就無法獲取到Authentication了。因?yàn)檫@時(shí)Feign調(diào)用是在調(diào)用方的調(diào)用線程下又開啟了一個(gè)子線程中進(jìn)行的。由于我使用的熔斷組件是Resilience4J,對(duì)應(yīng)的線程執(zhí)行源碼是Resilience4JCircuitBreaker下面的片段:
1
|
Supplier<Future<T>> futureSupplier = () -> executorService.submit(toRun::get); |
SecurityContextHolder保存信息是默認(rèn)是通過ThreadLocal實(shí)現(xiàn)的,我們都知道這個(gè)是不能跨線程的,而Feign的攔截器這時(shí)恰恰在子線程中,因此開啟了熔斷功能(circuitBreaker)的Feign無法直接進(jìn)行令牌中繼。
熔斷組件有過時(shí)的Hystrix、Resilience4J、還有阿里的哨兵Sentinel,它們的機(jī)制可能有小小的不同。
實(shí)現(xiàn)令牌中繼
雖然直接不能實(shí)現(xiàn)令牌中繼,但是我從中還是找到了一些信息。在Feign接口代理的處理器FeignCircuitBreakerInvocationHandler中發(fā)現(xiàn)了下面的代碼:
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代理類的執(zhí)行代碼,我們可以看到在執(zhí)行前:
1
|
final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); |
這里是獲得調(diào)用線程中請(qǐng)求的信息,包含了ServletHttpRequest、ServletHttpResponse等信息。緊接著又在lambda代碼中把這些信息又Setter了進(jìn)去:
1
|
RequestContextHolder.setRequestAttributes(requestAttributes); |
如果這是一個(gè)線程中進(jìn)行的簡(jiǎn)直就是吃飽了撐的,事實(shí)上Supplier返回值是在另一個(gè)線程中執(zhí)行的。這樣做的目的就是為了跨線程保存一些請(qǐng)求的元數(shù)據(jù)。
InheritableThreadLocal
RequestContextHolder 是如何做到跨線程了傳遞數(shù)據(jù)的呢?
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 維護(hù)了兩個(gè)容器,一個(gè)是不能跨線程的ThreadLocal,一個(gè)是實(shí)現(xiàn)了InheritableThreadLocal的NamedInheritableThreadLocal。InheritableThreadLocal是可以把父線程的數(shù)據(jù)傳遞到子線程的,基于這個(gè)原理RequestContextHolder把調(diào)用方的請(qǐng)求信息帶進(jìn)了子線程,借助于這個(gè)原理就能實(shí)現(xiàn)令牌中繼了。
實(shí)現(xiàn)令牌中繼
把最開始的Feign攔截器代碼改動(dòng)了一下就實(shí)現(xiàn)了令牌的中繼:
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); } } } } |
這樣當(dāng)你調(diào)用FooClient.bar()時(shí),在foo-service中資源服務(wù)器(OAuth2 Resource Server)也可以獲得調(diào)用方的令牌,進(jìn)而獲得用戶的信息來處理資源權(quán)限和業(yè)務(wù)。
不要忘記將這個(gè)攔截器注入Spring IoC。
總結(jié)
微服務(wù)令牌中繼是非常重要的,保證了用戶狀態(tài)在調(diào)用鏈路的傳遞。而且這也是微服務(wù)的難點(diǎn)。今天借助于Feign的一些特性和ThreadLocal的特性實(shí)現(xiàn)了令牌中繼供大家參考。
到此這篇關(guān)于JWT在OpenFeign調(diào)用中進(jìn)行令牌中繼的文章就介紹到這了,更多相關(guān)JWT OpenFeign令牌中繼內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://juejin.cn/post/7023246872147918885