grpc-auth-support.md 3.1 KB

Authentication

As outlined in the gRPC authentication guide there are a number of different mechanisms for asserting identity between an client and server. We'll present some code-samples here demonstrating how to provide TLS support encryption and identity assertions as well as passing OAuth2 tokens to services that support it.

Enabling TLS on a gRPC client

conn, err := grpc.Dial(serverAddr, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")))

Enabling TLS on a gRPC server

creds, err := credentials.NewServerTLSFromFile(certFile, keyFile)
if err != nil {
  log.Fatalf("Failed to generate credentials %v", err)
}
lis, err := net.Listen("tcp", ":0")
server := grpc.NewServer(grpc.Creds(creds))
...
server.Serve(lis)

OAuth2

For an example of how to configure client and server to use OAuth2 tokens, see here.

Validating a token on the server

Clients may use metadata.MD to store tokens and other authentication-related data. To gain access to the metadata.MD object, a server may use metadata.FromIncomingContext. With a reference to metadata.MD on the server, one needs to simply lookup the authorization key. Note, all keys stored within metadata.MD are normalized to lowercase. See here.

It is possible to configure token validation for all RPCs using an interceptor. A server may configure either a grpc.UnaryInterceptor or a grpc.StreamInterceptor.

Adding a token to all outgoing client RPCs

To send an OAuth2 token with each RPC, a client may configure the grpc.DialOption grpc.WithPerRPCCredentials. Alternatively, a client may also use the grpc.CallOption grpc.PerRPCCredentials on each invocation of an RPC.

To create a credentials.PerRPCCredentials, use oauth.NewOauthAccess. Note, the OAuth2 implementation of grpc.PerRPCCredentials requires a client to use grpc.WithTransportCredentials to prevent any insecure transmission of tokens.

Authenticating with Google

Google Compute Engine (GCE)

conn, err := grpc.Dial(serverAddr, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")), grpc.WithPerRPCCredentials(oauth.NewComputeEngine()))

JWT

jwtCreds, err := oauth.NewServiceAccountFromFile(*serviceAccountKeyFile, *oauthScope)
if err != nil {
  log.Fatalf("Failed to create JWT credentials: %v", err)
}
conn, err := grpc.Dial(serverAddr, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")), grpc.WithPerRPCCredentials(jwtCreds))