[英]How do I pass bearer token and other info from Spring Service to Grpc Interceptor?
我有一个 Spring GraphQL 应用程序,它使用 gRPC 协议调用其他内部微服务。 我需要将不记名令牌和其他信息设置为 gRPC header,我相信我们可以使用 gRPC 拦截器( ClientInterceptor
实现)来设置它。
我尝试了以下方法:
基于How to Access attributes from grpc Context.current()? 我创建了一个密钥,以便我们可以在 spring-service 和拦截器中引用它
public class ContextKeyHolder {
public static Context.Key<String> USER_INFO = Context.key("USER");
public static Context.Key<String> BEARER = Context.key("BEARER");
}
// spring-service method
public Employee getEmployee() {
...
Context.current().withValue(ContextKeyHolder.USER_INFO, currentUser.getUsername());
Context.current().withValue(ContextKeyHolder.BEARER, currentUser.getBearerToken());
return grpcClient.getEmployee(...);
}
// interceptCall implementation
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> methodDescriptor,
CallOptions callOptions, Channel channel) {
return new ForwardingClientCall.SimpleForwardingClientCall<>(
channel.newCall(methodDescriptor, callOptions)) {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
...
String userInfo = ContextKeyHolder.USER_INFO.get(Context.current());
System.out.println("user => " + userInfo);
...
super.start(responseListener, headers);
}
};
}
在这里,我在拦截器方法中获取null
userInfo。 我在这里错过了什么吗?
另一种选择是使用 ThreadLocal 来保存上下文,但我不确定这是否是正确的选择。
调用时需要使用您创建的上下文。 所以你的代码应该是:
return Context.current()
.withValue(ContextKeyHolder.USER_INFO, currentUser.getUsername())
.withValue(ContextKeyHolder.BEARER, currentUser.getBearerToken())
.call(() -> { return grpcClient.getEmployee(...);});
或者:
Context oldContext =
Context.current()
.withValue(ContextKeyHolder.USER_INFO, currentUser.getUsername())
.withValue(ContextKeyHolder.BEARER, currentUser.getBearerToken())
.attach();
Employee valueToReturn = grpcClient.getEmployee(...);
Context.current().detach(oldContext);
return valueToReturn;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.