[英]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.