Implementing gRPC Authentication
1. Understanding gRPC Security Model
| Layer | Mechanism |
|---|---|
| Transport | TLS/mTLS |
| Per-call | Metadata credentials (Bearer, JWT) |
| Cluster | ALTS (Google), Service Mesh (Istio/Linkerd) |
| App-level | Interceptors |
2. Implementing TLS for gRPC
Example: Server TLS
Server server = ServerBuilder.forPort(9090)
.useTransportSecurity(new File("server.crt"), new File("server.key"))
.addService(new MyService())
.build();
3. Using Token-Based Authentication
Example: Bearer in metadata
Metadata md = new Metadata();
md.put(Metadata.Key.of("authorization", ASCII_STRING_MARSHALLER), "Bearer " + jwt);
MyServiceGrpc.newBlockingStub(channel)
.withCallCredentials(MoreCallCredentials.from(googleCreds))
.myMethod(req);
4. Implementing Metadata Credentials
| API | Detail |
|---|---|
| CallCredentials | Per-RPC token attachment |
| ChannelCredentials | Transport-level (TLS) |
| CompositeCallCredentials | Combine multiple |
5. Using Client Certificates
| Step | Detail |
|---|---|
| Server | .clientAuth(REQUIRE) with trust manager |
| Client | Provide cert+key chain |
| SAN | SPIFFE ID in SubjectAltName URI |
6. Implementing Interceptors for Authorization
Example: ServerInterceptor
public class AuthInterceptor implements ServerInterceptor {
public <Req, Resp> Listener<Req> interceptCall(ServerCall<Req,Resp> call, Metadata headers, ServerCallHandler<Req,Resp> next) {
String auth = headers.get(AUTH_KEY);
if (auth == null || !auth.startsWith("Bearer ")) {
call.close(Status.UNAUTHENTICATED, new Metadata()); return new NoopListener<>();
}
Context ctx = Context.current().withValue(USER_CTX, verify(auth.substring(7)));
return Contexts.interceptCall(ctx, call, headers, next);
}
}
7. Using Per-RPC Credentials
Attached to individual calls via withCallCredentials — useful when single channel serves multiple identities.
8. Implementing ALTS
| Aspect | Detail |
|---|---|
| Full name | Application Layer Transport Security (Google) |
| Use | GCP service-to-service inside Google infra |
| Identity | Service account-based |
9. Handling Errors in gRPC
| Status Code | Maps to |
|---|---|
| UNAUTHENTICATED (16) | HTTP 401 |
| PERMISSION_DENIED (7) | HTTP 403 |
| UNAVAILABLE (14) | HTTP 503 |
10. Implementing Service-to-Service Auth
| Pattern | Detail |
|---|---|
| SPIFFE/SPIRE | Workload identity with X.509-SVID/JWT-SVID |
| mTLS via mesh | Istio peer authentication |
| Token exchange | RFC 8693 for user context propagation |