You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 2.3 KiB

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