Chapter 17: Authentication — TLS, mTLS, Token-Based
TLS (Server Authentication)
// Server: load certificate and key
grpc::SslServerCredentialsOptions opts;
opts.pem_root_certs = ca_cert;
opts.pem_key_cert_pairs.push_back({server_key, server_cert});
auto creds = grpc::SslServerCredentials(opts);
builder.AddListeningPort("0.0.0.0:443", creds);
// Client: verify server certificate
grpc::SslCredentialsOptions opts;
opts.pem_root_certs = ca_cert; // CA that signed server cert
auto creds = grpc::SslCredentials(opts);
auto channel = grpc::CreateChannel("server:443", creds);
mTLS (Mutual Authentication)
Both client AND server present certificates. Used for service-to-service auth.
// Client also provides its certificate:
opts.pem_private_key = client_key;
opts.pem_cert_chain = client_cert;
Token-Based (JWT/OAuth2)
// Client: attach token via metadata (interceptor)
ctx.AddMetadata("authorization", "Bearer " + jwt_token);
// Server: validate token (interceptor)
auto md = ctx->client_metadata();
auto token = md.find("authorization");
if (!validate_jwt(token->second)) {
return Status(UNAUTHENTICATED, "invalid token");
}