JWT如何在OpenFeign调用中进行令牌中继

3,652 阅读4分钟

小知识,大挑战!本文正在参与“    程序员必备小知识    ”创作活动

本文同时参与 「掘力星计划」    ,赢取创作大礼包,挑战创作激励金

下方留言,掘金官方送周边啦 博文中哪里写的不好的欢迎评论区指出 掘金官方抽送100个周边啦

在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接口:

@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,它们的机制可能有小小的不同。

实现令牌中继

虽然直接不能实现令牌中继,但是我从中还是找到了一些信息。在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();

这里是获得调用线程中请求的信息,包含了ServletHttpRequestServletHttpResponse等信息。紧接着又在lambda代码中把这些信息又Setter了进去:

	RequestContextHolder.setRequestAttributes(requestAttributes);

如果这是一个线程中进行的简直就是吃饱了撑的,事实上Supplier返回值是在另一个线程中执行的。这样做的目的就是为了跨线程保存一些请求的元数据。

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,一个是实现了InheritableThreadLocalNamedInheritableThreadLocalInheritableThreadLocal是可以把父线程的数据传递到子线程的,基于这个原理RequestContextHolder把调用方的请求信息带进了子线程,借助于这个原理就能实现令牌中继了。

实现令牌中继

把最开始的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。

总结

微服务令牌中继是非常重要的,保证了用户状态在调用链路的传递。而且这也是微服务的难点。今天借助于Feign的一些特性和ThreadLocal的特性实现了令牌中继供大家参考。原创不易,请大家多多点赞、评论。