使用
ServerInterceptor,然后通过传播身份
Context。这使您可以制定中央身份验证策略。
拦截器可以从中检索身份
metadata headers。 然后, 它 应该验证
身份。然后可以
testHello通过
io.grpc.Context以下方式将经过验证的身份传达给应用程序(即):
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 interceptorServer server = ServerBuilder.forPort(PORT) .addService(ServerInterceptors.intercept(new TestImpl(), new MyAuthInterceptor())) .build() .start();


