util.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2017 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package grpcproxy
  15. import (
  16. "context"
  17. "google.golang.org/grpc"
  18. "google.golang.org/grpc/metadata"
  19. )
  20. func getAuthTokenFromClient(ctx context.Context) string {
  21. md, ok := metadata.FromIncomingContext(ctx)
  22. if ok {
  23. ts, ok := md["token"]
  24. if ok {
  25. return ts[0]
  26. }
  27. }
  28. return ""
  29. }
  30. func withClientAuthToken(ctx context.Context, ctxWithToken context.Context) context.Context {
  31. token := getAuthTokenFromClient(ctxWithToken)
  32. if token != "" {
  33. ctx = context.WithValue(ctx, "token", token)
  34. }
  35. return ctx
  36. }
  37. type proxyTokenCredential struct {
  38. token string
  39. }
  40. func (cred *proxyTokenCredential) RequireTransportSecurity() bool {
  41. return false
  42. }
  43. func (cred *proxyTokenCredential) GetRequestMetadata(ctx context.Context, s ...string) (map[string]string, error) {
  44. return map[string]string{
  45. "token": cred.token,
  46. }, nil
  47. }
  48. func AuthUnaryClientInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
  49. token := getAuthTokenFromClient(ctx)
  50. if token != "" {
  51. tokenCred := &proxyTokenCredential{token}
  52. opts = append(opts, grpc.PerRPCCredentials(tokenCred))
  53. }
  54. return invoker(ctx, method, req, reply, cc, opts...)
  55. }
  56. func AuthStreamClientInterceptor(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
  57. tokenif := ctx.Value("token")
  58. if tokenif != nil {
  59. tokenCred := &proxyTokenCredential{tokenif.(string)}
  60. opts = append(opts, grpc.PerRPCCredentials(tokenCred))
  61. }
  62. return streamer(ctx, desc, cc, method, opts...)
  63. }