_auth.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # Copyright 2016 gRPC 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. """GRPCAuthMetadataPlugins for standard authentication."""
  15. import inspect
  16. import sys
  17. import grpc
  18. def _sign_request(callback, token, error):
  19. metadata = (('authorization', 'Bearer {}'.format(token)),)
  20. callback(metadata, error)
  21. class GoogleCallCredentials(grpc.AuthMetadataPlugin):
  22. """Metadata wrapper for GoogleCredentials from the oauth2client library."""
  23. def __init__(self, credentials):
  24. self._credentials = credentials
  25. # Hack to determine if these are JWT creds and we need to pass
  26. # additional_claims when getting a token
  27. if sys.version_info[0] == 2:
  28. args = inspect.getargspec(credentials.get_access_token).args
  29. else:
  30. args = inspect.getfullargspec(credentials.get_access_token).args
  31. self._is_jwt = 'additional_claims' in args
  32. def __call__(self, context, callback):
  33. try:
  34. if self._is_jwt:
  35. access_token = self._credentials.get_access_token(
  36. additional_claims={
  37. 'aud': context.service_url
  38. }).access_token
  39. else:
  40. access_token = self._credentials.get_access_token().access_token
  41. except Exception as exception: # pylint: disable=broad-except
  42. _sign_request(callback, None, exception)
  43. else:
  44. _sign_request(callback, access_token, None)
  45. class AccessTokenAuthMetadataPlugin(grpc.AuthMetadataPlugin):
  46. """Metadata wrapper for raw access token credentials."""
  47. def __init__(self, access_token):
  48. self._access_token = access_token
  49. def __call__(self, context, callback):
  50. _sign_request(callback, self._access_token, None)