api_key.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # Copyright 2022 Google LLC
  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. """Google API key support.
  15. This module provides authentication using the `API key`_.
  16. .. _API key:
  17. https://cloud.google.com/docs/authentication/api-keys/
  18. """
  19. from google.auth import _helpers
  20. from google.auth import credentials
  21. from google.auth import exceptions
  22. class Credentials(credentials.Credentials):
  23. """API key credentials.
  24. These credentials use API key to provide authorization to applications.
  25. """
  26. def __init__(self, token):
  27. """
  28. Args:
  29. token (str): API key string
  30. Raises:
  31. ValueError: If the provided API key is not a non-empty string.
  32. """
  33. super(Credentials, self).__init__()
  34. if not token:
  35. raise exceptions.InvalidValue("Token must be a non-empty API key string")
  36. self.token = token
  37. @property
  38. def expired(self):
  39. return False
  40. @property
  41. def valid(self):
  42. return True
  43. @_helpers.copy_docstring(credentials.Credentials)
  44. def refresh(self, request):
  45. return
  46. def apply(self, headers, token=None):
  47. """Apply the API key token to the x-goog-api-key header.
  48. Args:
  49. headers (Mapping): The HTTP request headers.
  50. token (Optional[str]): If specified, overrides the current access
  51. token.
  52. """
  53. headers["x-goog-api-key"] = token or self.token
  54. def before_request(self, request, method, url, headers):
  55. """Performs credential-specific before request logic.
  56. Refreshes the credentials if necessary, then calls :meth:`apply` to
  57. apply the token to the x-goog-api-key header.
  58. Args:
  59. request (google.auth.transport.Request): The object used to make
  60. HTTP requests.
  61. method (str): The request's HTTP method or the RPC method being
  62. invoked.
  63. url (str): The request's URI or the RPC service's URI.
  64. headers (Mapping): The request's headers.
  65. """
  66. self.apply(headers)