util.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. type proxyTokenCredential struct {
  31. token string
  32. }
  33. func (cred *proxyTokenCredential) RequireTransportSecurity() bool {
  34. return false
  35. }
  36. func (cred *proxyTokenCredential) GetRequestMetadata(ctx context.Context, s ...string) (map[string]string, error) {
  37. return map[string]string{
  38. "token": cred.token,
  39. }, nil
  40. }
  41. func AuthUnaryClientInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
  42. token := getAuthTokenFromClient(ctx)
  43. if token != "" {
  44. tokenCred := &proxyTokenCredential{token}
  45. opts = append(opts, grpc.PerRPCCredentials(tokenCred))
  46. }
  47. return invoker(ctx, method, req, reply, cc, opts...)
  48. }