1# Authentication 2 3In grpc, authentication is abstracted as 4[`credentials.PerRPCCredentials`](https://godoc.org/google.golang.org/grpc/credentials#PerRPCCredentials). 5It usually also encompasses authorization. Users can configure it on a 6per-connection basis or a per-call basis. 7 8The example for authentication currently includes an example for using oauth2 9with grpc. 10 11## Try it 12 13``` 14go run server/main.go 15``` 16 17``` 18go run client/main.go 19``` 20 21## Explanation 22 23### OAuth2 24 25OAuth 2.0 Protocol is a widely used authentication and authorization mechanism 26nowadays. And grpc provides convenient APIs to configure OAuth to use with grpc. 27Please refer to the godoc: 28https://godoc.org/google.golang.org/grpc/credentials/oauth for details. 29 30#### Client 31 32On client side, users should first get a valid oauth token, and then call 33[`credentials.NewOauthAccess`](https://godoc.org/google.golang.org/grpc/credentials/oauth#NewOauthAccess) 34to initialize a `credentials.PerRPCCredentials` with it. Next, if user wants to 35apply a single OAuth token for all RPC calls on the same connection, then 36configure grpc `Dial` with `DialOption` 37[`WithPerRPCCredentials`](https://godoc.org/google.golang.org/grpc#WithPerRPCCredentials). 38Or, if user wants to apply OAuth token per call, then configure the grpc RPC 39call with `CallOption` 40[`PerRPCCredentials`](https://godoc.org/google.golang.org/grpc#PerRPCCredentials). 41 42Note that OAuth requires the underlying transport to be secure (e.g. TLS, etc.) 43 44Inside grpc, the provided token is prefixed with the token type and a space, and 45is then attached to the metadata with the key "authorization". 46 47### Server 48 49On server side, users usually get the token and verify it inside an interceptor. 50To get the token, call 51[`metadata.FromIncomingContext`](https://godoc.org/google.golang.org/grpc/metadata#FromIncomingContext) 52on the given context. It returns the metadata map. Next, use the key 53"authorization" to get corresponding value, which is a slice of strings. For 54OAuth, the slice should only contain one element, which is a string in the 55format of <token-type> + " " + <token>. Users can easily get the token by 56parsing the string, and then verify the validity of it. 57 58If the token is not valid, returns an error with error code 59`codes.Unauthenticated`. 60 61If the token is valid, then invoke the method handler to start processing the 62RPC. 63