tree: 1be16e0c52d396440f90760b504be14ebfc2a7df [path history] [tgz]
  2. client/
  3. server/


In grpc, authentication is abstracted as credentials.PerRPCCredentials. It usually also encompasses authorization. Users can configure it on a per-connection basis or a per-call basis.

The example for authentication currently includes an example for using oauth2 with grpc.

Try it

go run server/main.go
go run client/main.go



OAuth 2.0 Protocol is a widely used authentication and authorization mechanism nowadays. And grpc provides convenient APIs to configure OAuth to use with grpc. Please refer to the godoc: for details.


On client side, users should first get a valid oauth token, and then call credentials.NewOauthAccess to initialize a credentials.PerRPCCredentials with it. Next, if user wants to apply a single OAuth token for all RPC calls on the same connection, then configure grpc Dial with DialOption WithPerRPCCredentials. Or, if user wants to apply OAuth token per call, then configure the grpc RPC call with CallOption PerRPCCredentials.

Note that OAuth requires the underlying transport to be secure (e.g. TLS, etc.)

Inside grpc, the provided token is prefixed with the token type and a space, and is then attached to the metadata with the key “authorization”.


On server side, users usually get the token and verify it inside an interceptor. To get the token, call metadata.FromIncomingContext on the given context. It returns the metadata map. Next, use the key “authorization” to get corresponding value, which is a slice of strings. For OAuth, the slice should only contain one element, which is a string in the format of + " " + . Users can easily get the token by parsing the string, and then verify the validity of it.

If the token is not valid, returns an error with error code codes.Unauthenticated.

If the token is valid, then invoke the method handler to start processing the RPC.