How do I access request metadata for a java grpc service I am defining?

后端 未结 1 450
悲哀的现实
悲哀的现实 2020-12-18 12:05

For some background, I am attempting to use grpc auth in order to provide security for some services I am defining.

Let\'s see if I can ask this is a way that makes

相关标签:
1条回答
  • 2020-12-18 12:39

    Use a ServerInterceptor and then propagate the identity via Context. This allows you to have a central policy for authentication.

    The interceptor can retrieve the identity from Metadata headers. It should then validate the identity. The validated identity can then be communicated to the application (i.e., testHello) via io.grpc.Context:

    /** Interceptor that validates user's identity. */
    class MyAuthInterceptor implements ServerInterceptor {
      public static final Context.Key<Object> USER_IDENTITY
          = Context.key("identity"); // "identity" is just for debugging
    
      @Override
      public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
          ServerCall<ReqT, RespT> call,
          Metadata headers,
          ServerCallHandler<ReqT, RespT> next) {
        // You need to implement validateIdentity
        Object identity = validateIdentity(headers);
        if (identity == null) { // this is optional, depending on your needs
          // Assume user not authenticated
          call.close(Status.UNAUTENTICATED.withDescription("some more info"),
                     new Metadata());
          return new ServerCall.Listener() {};
        }
        Context context = Context.current().withValue(USER_IDENTITY, identity);
        return Contexts.interceptCall(context, call, headers, next);
      }
    }
    
    public class TestImpl extends TestServiceGrpc.TestServiceImplBase {
      @Override
      public void testHello(TestRequest req, StreamObserver<TestResponse> responseObserver) {
        // Access to identity.
        Object identity = MyAuthInterceptor.USER_IDENTITY.get();
        ...
      }
    }
    
    // Need to use ServerInterceptors to enable the interceptor
    Server server = ServerBuilder.forPort(PORT)
        .addService(ServerInterceptors.intercept(new TestImpl(),
            new MyAuthInterceptor()))
        .build()
        .start();
    
    0 讨论(0)
提交回复
热议问题