Spring Cloud Feign如何實(shí)現(xiàn)JWT令牌中繼以傳遞認(rèn)證信息
令牌中繼
令牌中繼(Token Relay)是比較正式的說(shuō)法,說(shuō)白了就是讓Token令牌在服務(wù)間傳遞下去以保證資源服務(wù)器能夠正確地對(duì)調(diào)用方進(jìn)行鑒權(quán)。
令牌難道不能在Feign自動(dòng)中繼嗎?
如果我們攜帶Token去訪問(wèn)A服務(wù),A服務(wù)肯定能夠鑒權(quán),但是A服務(wù)又通過(guò)Feign調(diào)用B服務(wù),這時(shí)候A的令牌是無(wú)法直接傳遞給B服務(wù)的。
這里來(lái)簡(jiǎn)單說(shuō)下原因,服務(wù)間的調(diào)用通過(guò)Feign接口來(lái)進(jìn)行。在調(diào)用方通常我們編寫(xiě)類(lèi)似下面的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();
- }
- }
- }
當(dāng)我們調(diào)用Feign接口后,會(huì)通過(guò)動(dòng)態(tài)代理來(lái)生成該接口的代理類(lèi)供我們調(diào)用。如果我們不打開(kāi)熔斷我們可以從Spring Security提供SecurityContext對(duì)象中提取到資源服務(wù)器的認(rèn)證對(duì)象JwtAuthenticationToken,它包含了JWT令牌然后我們可以通過(guò)實(shí)現(xiàn)Feign的攔截器接口RequestInterceptor把Token放在請(qǐng)求頭中,偽代碼如下:
- /**
- * 需要注入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);
- }
- }
- }
如果我們不開(kāi)啟熔斷這樣搞問(wèn)題不大,為了防止調(diào)用鏈雪崩服務(wù)熔斷基本沒(méi)有不打開(kāi)的。這時(shí)候從SecurityContextHolder就無(wú)法獲取到Authentication了。因?yàn)檫@時(shí)Feign調(diào)用是在調(diào)用方的調(diào)用線程下又開(kāi)啟了一個(gè)子線程中進(jìn)行的。由于我使用的熔斷組件是Resilience4J,對(duì)應(yīng)的線程源碼在Resilience4JCircuitBreaker中:
- Supplier<Future<T>> futureSupplier = () -> executorService.submit(toRun::get);
SecurityContextHolder保存信息是默認(rèn)是通過(guò)ThreadLocal實(shí)現(xiàn)的,我們都知道這個(gè)是不能跨線程的,而Feign的攔截器這時(shí)恰恰在子線程中,因此開(kāi)啟了熔斷功能(circuitBreaker)的Feign無(wú)法直接進(jìn)行令牌中繼。
熔斷組件有過(guò)時(shí)的Hystrix、Resilience4J、還有阿里的哨兵Sentinel,它們的機(jī)制可能有小小的不同。
實(shí)現(xiàn)令牌中繼
雖然直接不能實(shí)現(xiàn)令牌中繼,但是我從中還是找到了一些信息。在Feign接口代理的處理器FeignCircuitBreakerInvocationHandler中發(fā)現(xiàn)了下面的代碼:
- 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代理類(lèi)的執(zhí)行代碼,我們可以看到在執(zhí)行前:
- final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
這里是獲得調(diào)用線程中請(qǐng)求的信息,包含了ServletHttpRequest、ServletHttpResponse等信息。緊接著又在lambda代碼中把這些信息又Setter了進(jìn)去:
- RequestContextHolder.setRequestAttributes(requestAttributes);
如果這是一個(gè)線程中進(jìn)行的簡(jiǎn)直就是吃飽了撐的,事實(shí)上Supplier返回值是在另一個(gè)線程中執(zhí)行的。這樣做的目的就是為了跨線程保存一些請(qǐng)求的元數(shù)據(jù)。
InheritableThreadLocal
- 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)令牌中繼
把最開(kāi)始的Feign攔截器代碼改動(dòng)了一下就實(shí)現(xiàn)了令牌的中繼:
- /**
- * 令牌中繼
- */
- 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)而獲得用戶(hù)的信息來(lái)處理資源權(quán)限和業(yè)務(wù)。
不要忘記將這個(gè)攔截器注入Spring IoC。
總結(jié)
微服務(wù)令牌中繼是非常重要的,保證了用戶(hù)狀態(tài)在調(diào)用鏈路的傳遞。而且這也是微服務(wù)的難點(diǎn)。今天借助于Feign的一些特性和ThreadLocal的特性實(shí)現(xiàn)了令牌中繼供大家參考。