如何访问正在定义的java grpc服务的请求元数据?

2024-09-30 12:24:28 发布

您现在位置:Python中文网/ 问答频道 /正文

对于某些背景,我尝试使用grpc auth为我定义的某些服务提供安全性。在

让我们看看我能不能问一下这是一个有意义的方法。对于python代码,实现服务器端代码非常容易。在

class TestServiceServer(service_pb2.TestServiceServer):

    def TestHello(self, request, context):

        ## credential metadata for the incoming request
        metadata = context.invocation_metadata()

        ## authenticate the user using the metadata

因此,正如您所说,我可以很容易地从“context”中获取元数据。对我来说更难的是在java中做同样的事情。在

^{pr2}$

我承认我的问题来自几个方面。在

1)我不太精通Java

2)我大量使用python的“pdb”来调试类,看看有什么方法对我可用。我不知道/不精通类似的java工具。在

3)在这一点上,文档似乎相当稀少。它向您展示了如何在服务器端设置ssl连接,但是我找不到服务器查看请求元数据的示例,正如我在python中所展示的那样。在

有人能告诉我如何做到这一点,或者向我展示一个有用的java调试工具,与python的pdb相同?在

编辑/回答:

我需要首先编写一个实现接口ServerInterceptor的定义。在

private class TestInterceptor implements ServerInterceptor {
    ....

然后,在实际绑定服务和构建服务器之前,我需要这样做。在

TestImpl service = new TestImpl();
ServerServiceDefinition intercepted = ServerInterceptors.intercept(service, new TestInterceptor());

现在我可以创建服务器了。在

server = NettyServerBuilder.forPort(port)

    // enable tls
    .useTransportSecurity(
        new File(serverCert),
        new File(serverKey)
    )
    .addService(
        intercepted  // had been "new TestImpl()"
    )
    .build();

server.start();

这使我的ServerInterceptor可以在我发出客户端请求时被调用。在

This link很有助于解决这个问题。在


Tags: the方法代码服务器new定义requestservice
1条回答
网友
1楼 · 发布于 2024-09-30 12:24:28

使用ServerInterceptor,然后通过Context传播标识。这允许您有一个用于身份验证的中心策略。在

拦截器可以从Metadata headers检索标识。然后,它应该验证身份。验证的身份然后可以通过io.grpc.Context传送给应用程序(即testHello):

/** 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();

相关问题 更多 >

    热门问题