[英]How do I pass bearer token and other info from Spring Service to Grpc Interceptor?
I have a Spring GraphQL application that calls the other internal microservice using the gRPC protocol.我有一个 Spring GraphQL 应用程序,它使用 gRPC 协议调用其他内部微服务。 I need to set the bearer token and other information to the gRPC header, I believe we can set it up using the gRPC interceptor (
ClientInterceptor
implementation).我需要将不记名令牌和其他信息设置为 gRPC header,我相信我们可以使用 gRPC 拦截器(
ClientInterceptor
实现)来设置它。
I tried the below approach:我尝试了以下方法:
Based on How to Access attributes from grpc Context.current()?基于How to Access attributes from grpc Context.current()? I created a key so that we can refer it in spring-service and interceptor
我创建了一个密钥,以便我们可以在 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);
}
};
}
Here I am getting null
userInfo in the interceptor method.在这里,我在拦截器方法中获取
null
userInfo。 am I missing something here?我在这里错过了什么吗?
The other option is to use ThreadLocal to hold the context but I am kind of not sure if it's the right choice here.另一种选择是使用 ThreadLocal 来保存上下文,但我不确定这是否是正确的选择。
The context you created needs to be used when you make the call.调用时需要使用您创建的上下文。 So your code should be:
所以你的代码应该是:
return Context.current()
.withValue(ContextKeyHolder.USER_INFO, currentUser.getUsername())
.withValue(ContextKeyHolder.BEARER, currentUser.getBearerToken())
.call(() -> { return grpcClient.getEmployee(...);});
Alternatively:或者:
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.