_credentials_base.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # Copyright 2024 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. """Interface for base credentials."""
  15. import abc
  16. from google.auth import _helpers
  17. class _BaseCredentials(metaclass=abc.ABCMeta):
  18. """Base class for all credentials.
  19. All credentials have a :attr:`token` that is used for authentication and
  20. may also optionally set an :attr:`expiry` to indicate when the token will
  21. no longer be valid.
  22. Most credentials will be :attr:`invalid` until :meth:`refresh` is called.
  23. Credentials can do this automatically before the first HTTP request in
  24. :meth:`before_request`.
  25. Although the token and expiration will change as the credentials are
  26. :meth:`refreshed <refresh>` and used, credentials should be considered
  27. immutable. Various credentials will accept configuration such as private
  28. keys, scopes, and other options. These options are not changeable after
  29. construction. Some classes will provide mechanisms to copy the credentials
  30. with modifications such as :meth:`ScopedCredentials.with_scopes`.
  31. Attributes:
  32. token (Optional[str]): The bearer token that can be used in HTTP headers to make
  33. authenticated requests.
  34. """
  35. def __init__(self):
  36. self.token = None
  37. @abc.abstractmethod
  38. def refresh(self, request):
  39. """Refreshes the access token.
  40. Args:
  41. request (google.auth.transport.Request): The object used to make
  42. HTTP requests.
  43. Raises:
  44. google.auth.exceptions.RefreshError: If the credentials could
  45. not be refreshed.
  46. """
  47. # pylint: disable=missing-raises-doc
  48. # (pylint doesn't recognize that this is abstract)
  49. raise NotImplementedError("Refresh must be implemented")
  50. def _apply(self, headers, token=None):
  51. """Apply the token to the authentication header.
  52. Args:
  53. headers (Mapping): The HTTP request headers.
  54. token (Optional[str]): If specified, overrides the current access
  55. token.
  56. """
  57. headers["authorization"] = "Bearer {}".format(
  58. _helpers.from_bytes(token or self.token)
  59. )