0Pricing
gRPC & High Performance APIs · 课时

用于安全防护的拦截器

使用 gRPC 拦截器集中处理各服务中的身份验证、日志记录等安全问题

用于安全防护的拦截器 是 CoddyKit 上的免费 gRPC & High Performance APIs 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 gRPC & High Performance APIs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 gRPC & High Performance APIs 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Intro to gRPC Interceptors

Interceptors are a powerful feature in gRPC, acting like middleware that can inspect and modify requests and responses. They allow you to centralize common logic that applies to multiple service calls.

Think of them as gates or checkpoints your requests pass through.

Why Use Interceptors?

Interceptors are perfect for handling cross-cutting concerns. Instead of repeating code in every service method, you can manage things like:

  • Authentication
  • Authorization
  • Logging & Monitoring
  • Request validation

This keeps your core service logic clean and focused.

Server Interceptors

A server interceptor sits between the gRPC server and your actual service implementation. It runs logic before your service method is called, allowing you to:

  • Validate incoming requests
  • Check authentication tokens
  • Add request context

Client Interceptors

A client interceptor operates on the client side, executing logic before a request is sent to the server. This is useful for:

  • Adding authentication tokens to outgoing requests
  • Injecting tracing headers
  • Implementing retry logic
  • Modifying request metadata

Server Interceptor Structure

On the server, an interceptor wraps the ServerCallHandler. It receives the ServerCall and Metadata, and can decide to proceed with the call or terminate it. Here's a conceptual view:

class AuthInterceptor implements ServerInterceptor {
  public <ReqT, RespT> ServerCall.Listener<ReqT>
      interceptCall(ServerCall<ReqT, RespT> call,
                    Metadata headers,
                    ServerCallHandler next) {
    // Check headers for auth token
    if (isValid(headers)) {
      return next.startCall(call, headers);
    } else {
      call.close(Status.UNAUTHENTICATED, headers);
      return new ServerCall.Listener<ReqT>() {}; // Block call
    }
  }
}

Client Interceptor Structure

On the client, an interceptor typically implements ClientInterceptor. It allows you to modify the CallOptions or Metadata before the actual RPC call is made.

class ApiKeyInterceptor implements ClientInterceptor {
  public <ReqT, RespT> ClientCall<ReqT, RespT>
      interceptCall(MethodDescriptor<ReqT, RespT> method,
                    CallOptions callOptions,
                    Channel next) {
    return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(
        next.newCall(method, callOptions)) {
      @Override
      public void start(ClientCall.Listener<RespT> responseListener,
                        Metadata headers) {
        // Add API key to headers
        headers.put(API_KEY_METADATA_KEY, "my-secret-key");
        super.start(responseListener, headers);
      }
    };
  }
}

Simulated Server Auth Check

Let's simulate a server interceptor checking for an authentication token. If the token is missing or invalid, the 'request' is blocked and the service method isn't called.

public class Main {
    // Simulate an interceptor's core logic
    static void authInterceptor(String metadata, Runnable nextCall) {
        System.out.println("Interceptor: Checking metadata...");
        if (metadata != null && metadata.contains("auth_token:valid")) {
            System.out.println("Interceptor: Authentication successful!");
            nextCall.run(); // Proceed to the actual service method
        } else {
            System.out.println("Interceptor: Authentication failed! Request blocked.");
        }
    }

    // Simulate the actual service method
    static void actualServiceMethod() {
        System.out.println("Service: Request processed successfully!");
    }

    public static void main(String[] args) {
        System.out.println("--- Valid Request ---");
        authInterceptor("auth_token:valid", Main::actualServiceMethod);

        System.out.println("\n--- Invalid Request ---");
        authInterceptor("auth_token:invalid", Main::actualServiceMethod);

        System.out.println("\n--- Missing Token ---");
        authInterceptor(null, Main::actualServiceMethod);
    }
}

Simulated Client API Key

Now, let's simulate a client interceptor that automatically adds an API key to the request metadata before it's sent to the server. This ensures every call includes necessary credentials.

public class Main {
    // Simulate an interceptor that adds metadata
    static String addApiKeyInterceptor(String existingMetadata, String apiKey, String methodName) {
        System.out.println("Client Interceptor: Adding API key for " + methodName);
        return (existingMetadata != null ? existingMetadata + ", " : "") + "api_key:" + apiKey;
    }

    // Simulate sending a request
    static void sendRequest(String metadata, String methodName) {
        System.out.println("Client: Sending request to " + methodName + " with metadata: [" + metadata + "]");
        // In a real gRPC call, this metadata would be sent to the server
    }

    public static void main(String[] args) {
        String initialMetadata = "user_id:123";
        String apiKey = "my_secret_key_123";
        String targetMethod = "/MyService/SayHello";

        // Apply client interceptor
        String finalMetadata = addApiKeyInterceptor(initialMetadata, apiKey, targetMethod);

        // Send the request with enhanced metadata
        sendRequest(finalMetadata, targetMethod);
    }
}

Chaining Interceptors

You can apply multiple interceptors to a gRPC channel or server. They form a chain, executing in the order they are added. This allows for modular and layered processing of requests.

  • The first interceptor processes, then passes to the second.
  • The second processes, then passes to the service (or the next interceptor).
  • The order in which you add interceptors matters!

Interceptor Use Cases

Interceptors are highly versatile for enhancing your gRPC services. Which of these are common security-related use cases for gRPC interceptors?

Recap: Interceptors for Security

Interceptors provide a powerful, centralized way to inject logic into your gRPC request and response flow. They are invaluable for implementing security features like authentication, authorization, and auditing, keeping your service code clean and focused on business logic.

By using interceptors, you build more robust, maintainable, and secure gRPC applications.

常见问题解答

「用于安全防护的拦截器」课时是免费的吗?

是的 — 「用于安全防护的拦截器」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 gRPC & High Performance APIs 课程的其余内容,请升级到 CoddyKit PRO。 gRPC & High Performance APIs 课程共包含 4 节课。

「用于安全防护的拦截器」这节课中我会学到什么?

使用 gRPC 拦截器集中处理各服务中的身份验证、日志记录等安全问题 你通过在浏览器中直接运行的动手代码来练习 gRPC & High Performance APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 gRPC & High Performance APIs 需要有经验吗?

无需任何先前经验。CoddyKit 上的 gRPC & High Performance APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「用于安全防护的拦截器」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 gRPC & High Performance APIs 课中编写并运行代码吗?

能。每节 gRPC & High Performance APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. gRPC 的 TLS/SSL
  2. 身份验证与授权
  3. 用于安全防护的拦截器
  4. 用于服务间身份验证的双向 TLS(mTLS)
← 返回 gRPC & High Performance APIs