credentials.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. # Copyright 2016 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. """OAuth 2.0 Credentials.
  15. This module provides credentials based on OAuth 2.0 access and refresh tokens.
  16. These credentials usually access resources on behalf of a user (resource
  17. owner).
  18. Specifically, this is intended to use access tokens acquired using the
  19. `Authorization Code grant`_ and can refresh those tokens using a
  20. optional `refresh token`_.
  21. Obtaining the initial access and refresh token is outside of the scope of this
  22. module. Consult `rfc6749 section 4.1`_ for complete details on the
  23. Authorization Code grant flow.
  24. .. _Authorization Code grant: https://tools.ietf.org/html/rfc6749#section-1.3.1
  25. .. _refresh token: https://tools.ietf.org/html/rfc6749#section-6
  26. .. _rfc6749 section 4.1: https://tools.ietf.org/html/rfc6749#section-4.1
  27. """
  28. from datetime import datetime
  29. import io
  30. import json
  31. import logging
  32. import warnings
  33. from google.auth import _cloud_sdk
  34. from google.auth import _helpers
  35. from google.auth import credentials
  36. from google.auth import exceptions
  37. from google.auth import metrics
  38. from google.oauth2 import reauth
  39. _LOGGER = logging.getLogger(__name__)
  40. # The Google OAuth 2.0 token endpoint. Used for authorized user credentials.
  41. _GOOGLE_OAUTH2_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token"
  42. class Credentials(credentials.ReadOnlyScoped, credentials.CredentialsWithQuotaProject):
  43. """Credentials using OAuth 2.0 access and refresh tokens.
  44. The credentials are considered immutable except the tokens and the token
  45. expiry, which are updated after refresh. If you want to modify the quota
  46. project, use :meth:`with_quota_project` or ::
  47. credentials = credentials.with_quota_project('myproject-123')
  48. Reauth is disabled by default. To enable reauth, set the
  49. `enable_reauth_refresh` parameter to True in the constructor. Note that
  50. reauth feature is intended for gcloud to use only.
  51. If reauth is enabled, `pyu2f` dependency has to be installed in order to use security
  52. key reauth feature. Dependency can be installed via `pip install pyu2f` or `pip install
  53. google-auth[reauth]`.
  54. """
  55. def __init__(
  56. self,
  57. token,
  58. refresh_token=None,
  59. id_token=None,
  60. token_uri=None,
  61. client_id=None,
  62. client_secret=None,
  63. scopes=None,
  64. default_scopes=None,
  65. quota_project_id=None,
  66. expiry=None,
  67. rapt_token=None,
  68. refresh_handler=None,
  69. enable_reauth_refresh=False,
  70. granted_scopes=None,
  71. trust_boundary=None,
  72. universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN,
  73. account=None,
  74. ):
  75. """
  76. Args:
  77. token (Optional(str)): The OAuth 2.0 access token. Can be None
  78. if refresh information is provided.
  79. refresh_token (str): The OAuth 2.0 refresh token. If specified,
  80. credentials can be refreshed.
  81. id_token (str): The Open ID Connect ID Token.
  82. token_uri (str): The OAuth 2.0 authorization server's token
  83. endpoint URI. Must be specified for refresh, can be left as
  84. None if the token can not be refreshed.
  85. client_id (str): The OAuth 2.0 client ID. Must be specified for
  86. refresh, can be left as None if the token can not be refreshed.
  87. client_secret(str): The OAuth 2.0 client secret. Must be specified
  88. for refresh, can be left as None if the token can not be
  89. refreshed.
  90. scopes (Sequence[str]): The scopes used to obtain authorization.
  91. This parameter is used by :meth:`has_scopes`. OAuth 2.0
  92. credentials can not request additional scopes after
  93. authorization. The scopes must be derivable from the refresh
  94. token if refresh information is provided (e.g. The refresh
  95. token scopes are a superset of this or contain a wild card
  96. scope like 'https://www.googleapis.com/auth/any-api').
  97. default_scopes (Sequence[str]): Default scopes passed by a
  98. Google client library. Use 'scopes' for user-defined scopes.
  99. quota_project_id (Optional[str]): The project ID used for quota and billing.
  100. This project may be different from the project used to
  101. create the credentials.
  102. rapt_token (Optional[str]): The reauth Proof Token.
  103. refresh_handler (Optional[Callable[[google.auth.transport.Request, Sequence[str]], [str, datetime]]]):
  104. A callable which takes in the HTTP request callable and the list of
  105. OAuth scopes and when called returns an access token string for the
  106. requested scopes and its expiry datetime. This is useful when no
  107. refresh tokens are provided and tokens are obtained by calling
  108. some external process on demand. It is particularly useful for
  109. retrieving downscoped tokens from a token broker.
  110. enable_reauth_refresh (Optional[bool]): Whether reauth refresh flow
  111. should be used. This flag is for gcloud to use only.
  112. granted_scopes (Optional[Sequence[str]]): The scopes that were consented/granted by the user.
  113. This could be different from the requested scopes and it could be empty if granted
  114. and requested scopes were same.
  115. trust_boundary (str): String representation of trust boundary meta.
  116. universe_domain (Optional[str]): The universe domain. The default
  117. universe domain is googleapis.com.
  118. account (Optional[str]): The account associated with the credential.
  119. """
  120. super(Credentials, self).__init__()
  121. self.token = token
  122. self.expiry = expiry
  123. self._refresh_token = refresh_token
  124. self._id_token = id_token
  125. self._scopes = scopes
  126. self._default_scopes = default_scopes
  127. self._granted_scopes = granted_scopes
  128. self._token_uri = token_uri
  129. self._client_id = client_id
  130. self._client_secret = client_secret
  131. self._quota_project_id = quota_project_id
  132. self._rapt_token = rapt_token
  133. self.refresh_handler = refresh_handler
  134. self._enable_reauth_refresh = enable_reauth_refresh
  135. self._trust_boundary = trust_boundary
  136. self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN
  137. self._account = account or ""
  138. def __getstate__(self):
  139. """A __getstate__ method must exist for the __setstate__ to be called
  140. This is identical to the default implementation.
  141. See https://docs.python.org/3.7/library/pickle.html#object.__setstate__
  142. """
  143. state_dict = self.__dict__.copy()
  144. # Remove _refresh_handler function as there are limitations pickling and
  145. # unpickling certain callables (lambda, functools.partial instances)
  146. # because they need to be importable.
  147. # Instead, the refresh_handler setter should be used to repopulate this.
  148. if "_refresh_handler" in state_dict:
  149. del state_dict["_refresh_handler"]
  150. if "_refresh_worker" in state_dict:
  151. del state_dict["_refresh_worker"]
  152. return state_dict
  153. def __setstate__(self, d):
  154. """Credentials pickled with older versions of the class do not have
  155. all the attributes."""
  156. self.token = d.get("token")
  157. self.expiry = d.get("expiry")
  158. self._refresh_token = d.get("_refresh_token")
  159. self._id_token = d.get("_id_token")
  160. self._scopes = d.get("_scopes")
  161. self._default_scopes = d.get("_default_scopes")
  162. self._granted_scopes = d.get("_granted_scopes")
  163. self._token_uri = d.get("_token_uri")
  164. self._client_id = d.get("_client_id")
  165. self._client_secret = d.get("_client_secret")
  166. self._quota_project_id = d.get("_quota_project_id")
  167. self._rapt_token = d.get("_rapt_token")
  168. self._enable_reauth_refresh = d.get("_enable_reauth_refresh")
  169. self._trust_boundary = d.get("_trust_boundary")
  170. self._universe_domain = (
  171. d.get("_universe_domain") or credentials.DEFAULT_UNIVERSE_DOMAIN
  172. )
  173. # The refresh_handler setter should be used to repopulate this.
  174. self._refresh_handler = None
  175. self._refresh_worker = None
  176. self._use_non_blocking_refresh = d.get("_use_non_blocking_refresh", False)
  177. self._account = d.get("_account", "")
  178. @property
  179. def refresh_token(self):
  180. """Optional[str]: The OAuth 2.0 refresh token."""
  181. return self._refresh_token
  182. @property
  183. def scopes(self):
  184. """Optional[str]: The OAuth 2.0 permission scopes."""
  185. return self._scopes
  186. @property
  187. def granted_scopes(self):
  188. """Optional[Sequence[str]]: The OAuth 2.0 permission scopes that were granted by the user."""
  189. return self._granted_scopes
  190. @property
  191. def token_uri(self):
  192. """Optional[str]: The OAuth 2.0 authorization server's token endpoint
  193. URI."""
  194. return self._token_uri
  195. @property
  196. def id_token(self):
  197. """Optional[str]: The Open ID Connect ID Token.
  198. Depending on the authorization server and the scopes requested, this
  199. may be populated when credentials are obtained and updated when
  200. :meth:`refresh` is called. This token is a JWT. It can be verified
  201. and decoded using :func:`google.oauth2.id_token.verify_oauth2_token`.
  202. """
  203. return self._id_token
  204. @property
  205. def client_id(self):
  206. """Optional[str]: The OAuth 2.0 client ID."""
  207. return self._client_id
  208. @property
  209. def client_secret(self):
  210. """Optional[str]: The OAuth 2.0 client secret."""
  211. return self._client_secret
  212. @property
  213. def requires_scopes(self):
  214. """False: OAuth 2.0 credentials have their scopes set when
  215. the initial token is requested and can not be changed."""
  216. return False
  217. @property
  218. def rapt_token(self):
  219. """Optional[str]: The reauth Proof Token."""
  220. return self._rapt_token
  221. @property
  222. def refresh_handler(self):
  223. """Returns the refresh handler if available.
  224. Returns:
  225. Optional[Callable[[google.auth.transport.Request, Sequence[str]], [str, datetime]]]:
  226. The current refresh handler.
  227. """
  228. return self._refresh_handler
  229. @refresh_handler.setter
  230. def refresh_handler(self, value):
  231. """Updates the current refresh handler.
  232. Args:
  233. value (Optional[Callable[[google.auth.transport.Request, Sequence[str]], [str, datetime]]]):
  234. The updated value of the refresh handler.
  235. Raises:
  236. TypeError: If the value is not a callable or None.
  237. """
  238. if not callable(value) and value is not None:
  239. raise TypeError("The provided refresh_handler is not a callable or None.")
  240. self._refresh_handler = value
  241. @property
  242. def account(self):
  243. """str: The user account associated with the credential. If the account is unknown an empty string is returned."""
  244. return self._account
  245. @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
  246. def with_quota_project(self, quota_project_id):
  247. return self.__class__(
  248. self.token,
  249. refresh_token=self.refresh_token,
  250. id_token=self.id_token,
  251. token_uri=self.token_uri,
  252. client_id=self.client_id,
  253. client_secret=self.client_secret,
  254. scopes=self.scopes,
  255. default_scopes=self.default_scopes,
  256. granted_scopes=self.granted_scopes,
  257. quota_project_id=quota_project_id,
  258. rapt_token=self.rapt_token,
  259. enable_reauth_refresh=self._enable_reauth_refresh,
  260. trust_boundary=self._trust_boundary,
  261. universe_domain=self._universe_domain,
  262. account=self._account,
  263. )
  264. @_helpers.copy_docstring(credentials.CredentialsWithTokenUri)
  265. def with_token_uri(self, token_uri):
  266. return self.__class__(
  267. self.token,
  268. refresh_token=self.refresh_token,
  269. id_token=self.id_token,
  270. token_uri=token_uri,
  271. client_id=self.client_id,
  272. client_secret=self.client_secret,
  273. scopes=self.scopes,
  274. default_scopes=self.default_scopes,
  275. granted_scopes=self.granted_scopes,
  276. quota_project_id=self.quota_project_id,
  277. rapt_token=self.rapt_token,
  278. enable_reauth_refresh=self._enable_reauth_refresh,
  279. trust_boundary=self._trust_boundary,
  280. universe_domain=self._universe_domain,
  281. account=self._account,
  282. )
  283. def with_account(self, account):
  284. """Returns a copy of these credentials with a modified account.
  285. Args:
  286. account (str): The account to set
  287. Returns:
  288. google.oauth2.credentials.Credentials: A new credentials instance.
  289. """
  290. return self.__class__(
  291. self.token,
  292. refresh_token=self.refresh_token,
  293. id_token=self.id_token,
  294. token_uri=self._token_uri,
  295. client_id=self.client_id,
  296. client_secret=self.client_secret,
  297. scopes=self.scopes,
  298. default_scopes=self.default_scopes,
  299. granted_scopes=self.granted_scopes,
  300. quota_project_id=self.quota_project_id,
  301. rapt_token=self.rapt_token,
  302. enable_reauth_refresh=self._enable_reauth_refresh,
  303. trust_boundary=self._trust_boundary,
  304. universe_domain=self._universe_domain,
  305. account=account,
  306. )
  307. @_helpers.copy_docstring(credentials.CredentialsWithUniverseDomain)
  308. def with_universe_domain(self, universe_domain):
  309. return self.__class__(
  310. self.token,
  311. refresh_token=self.refresh_token,
  312. id_token=self.id_token,
  313. token_uri=self._token_uri,
  314. client_id=self.client_id,
  315. client_secret=self.client_secret,
  316. scopes=self.scopes,
  317. default_scopes=self.default_scopes,
  318. granted_scopes=self.granted_scopes,
  319. quota_project_id=self.quota_project_id,
  320. rapt_token=self.rapt_token,
  321. enable_reauth_refresh=self._enable_reauth_refresh,
  322. trust_boundary=self._trust_boundary,
  323. universe_domain=universe_domain,
  324. account=self._account,
  325. )
  326. def _metric_header_for_usage(self):
  327. return metrics.CRED_TYPE_USER
  328. @_helpers.copy_docstring(credentials.Credentials)
  329. def refresh(self, request):
  330. if self._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN:
  331. raise exceptions.RefreshError(
  332. "User credential refresh is only supported in the default "
  333. "googleapis.com universe domain, but the current universe "
  334. "domain is {}. If you created the credential with an access "
  335. "token, it's likely that the provided token is expired now, "
  336. "please update your code with a valid token.".format(
  337. self._universe_domain
  338. )
  339. )
  340. scopes = self._scopes if self._scopes is not None else self._default_scopes
  341. # Use refresh handler if available and no refresh token is
  342. # available. This is useful in general when tokens are obtained by calling
  343. # some external process on demand. It is particularly useful for retrieving
  344. # downscoped tokens from a token broker.
  345. if self._refresh_token is None and self.refresh_handler:
  346. token, expiry = self.refresh_handler(request, scopes=scopes)
  347. # Validate returned data.
  348. if not isinstance(token, str):
  349. raise exceptions.RefreshError(
  350. "The refresh_handler returned token is not a string."
  351. )
  352. if not isinstance(expiry, datetime):
  353. raise exceptions.RefreshError(
  354. "The refresh_handler returned expiry is not a datetime object."
  355. )
  356. if _helpers.utcnow() >= expiry - _helpers.REFRESH_THRESHOLD:
  357. raise exceptions.RefreshError(
  358. "The credentials returned by the refresh_handler are "
  359. "already expired."
  360. )
  361. self.token = token
  362. self.expiry = expiry
  363. return
  364. if (
  365. self._refresh_token is None
  366. or self._token_uri is None
  367. or self._client_id is None
  368. or self._client_secret is None
  369. ):
  370. raise exceptions.RefreshError(
  371. "The credentials do not contain the necessary fields need to "
  372. "refresh the access token. You must specify refresh_token, "
  373. "token_uri, client_id, and client_secret."
  374. )
  375. (
  376. access_token,
  377. refresh_token,
  378. expiry,
  379. grant_response,
  380. rapt_token,
  381. ) = reauth.refresh_grant(
  382. request,
  383. self._token_uri,
  384. self._refresh_token,
  385. self._client_id,
  386. self._client_secret,
  387. scopes=scopes,
  388. rapt_token=self._rapt_token,
  389. enable_reauth_refresh=self._enable_reauth_refresh,
  390. )
  391. self.token = access_token
  392. self.expiry = expiry
  393. self._refresh_token = refresh_token
  394. self._id_token = grant_response.get("id_token")
  395. self._rapt_token = rapt_token
  396. if scopes and "scope" in grant_response:
  397. requested_scopes = frozenset(scopes)
  398. self._granted_scopes = grant_response["scope"].split()
  399. granted_scopes = frozenset(self._granted_scopes)
  400. scopes_requested_but_not_granted = requested_scopes - granted_scopes
  401. if scopes_requested_but_not_granted:
  402. # User might be presented with unbundled scopes at the time of
  403. # consent. So it is a valid scenario to not have all the requested
  404. # scopes as part of granted scopes but log a warning in case the
  405. # developer wants to debug the scenario.
  406. _LOGGER.warning(
  407. "Not all requested scopes were granted by the "
  408. "authorization server, missing scopes {}.".format(
  409. ", ".join(scopes_requested_but_not_granted)
  410. )
  411. )
  412. @classmethod
  413. def from_authorized_user_info(cls, info, scopes=None):
  414. """Creates a Credentials instance from parsed authorized user info.
  415. Args:
  416. info (Mapping[str, str]): The authorized user info in Google
  417. format.
  418. scopes (Sequence[str]): Optional list of scopes to include in the
  419. credentials.
  420. Returns:
  421. google.oauth2.credentials.Credentials: The constructed
  422. credentials.
  423. Raises:
  424. ValueError: If the info is not in the expected format.
  425. """
  426. keys_needed = set(("refresh_token", "client_id", "client_secret"))
  427. missing = keys_needed.difference(info.keys())
  428. if missing:
  429. raise ValueError(
  430. "Authorized user info was not in the expected format, missing "
  431. "fields {}.".format(", ".join(missing))
  432. )
  433. # access token expiry (datetime obj); auto-expire if not saved
  434. expiry = info.get("expiry")
  435. if expiry:
  436. expiry = datetime.strptime(
  437. expiry.rstrip("Z").split(".")[0], "%Y-%m-%dT%H:%M:%S"
  438. )
  439. else:
  440. expiry = _helpers.utcnow() - _helpers.REFRESH_THRESHOLD
  441. # process scopes, which needs to be a seq
  442. if scopes is None and "scopes" in info:
  443. scopes = info.get("scopes")
  444. if isinstance(scopes, str):
  445. scopes = scopes.split(" ")
  446. return cls(
  447. token=info.get("token"),
  448. refresh_token=info.get("refresh_token"),
  449. token_uri=_GOOGLE_OAUTH2_TOKEN_ENDPOINT, # always overrides
  450. scopes=scopes,
  451. client_id=info.get("client_id"),
  452. client_secret=info.get("client_secret"),
  453. quota_project_id=info.get("quota_project_id"), # may not exist
  454. expiry=expiry,
  455. rapt_token=info.get("rapt_token"), # may not exist
  456. trust_boundary=info.get("trust_boundary"), # may not exist
  457. universe_domain=info.get("universe_domain"), # may not exist
  458. account=info.get("account", ""), # may not exist
  459. )
  460. @classmethod
  461. def from_authorized_user_file(cls, filename, scopes=None):
  462. """Creates a Credentials instance from an authorized user json file.
  463. Args:
  464. filename (str): The path to the authorized user json file.
  465. scopes (Sequence[str]): Optional list of scopes to include in the
  466. credentials.
  467. Returns:
  468. google.oauth2.credentials.Credentials: The constructed
  469. credentials.
  470. Raises:
  471. ValueError: If the file is not in the expected format.
  472. """
  473. with io.open(filename, "r", encoding="utf-8") as json_file:
  474. data = json.load(json_file)
  475. return cls.from_authorized_user_info(data, scopes)
  476. def to_json(self, strip=None):
  477. """Utility function that creates a JSON representation of a Credentials
  478. object.
  479. Args:
  480. strip (Sequence[str]): Optional list of members to exclude from the
  481. generated JSON.
  482. Returns:
  483. str: A JSON representation of this instance. When converted into
  484. a dictionary, it can be passed to from_authorized_user_info()
  485. to create a new credential instance.
  486. """
  487. prep = {
  488. "token": self.token,
  489. "refresh_token": self.refresh_token,
  490. "token_uri": self.token_uri,
  491. "client_id": self.client_id,
  492. "client_secret": self.client_secret,
  493. "scopes": self.scopes,
  494. "rapt_token": self.rapt_token,
  495. "universe_domain": self._universe_domain,
  496. "account": self._account,
  497. }
  498. if self.expiry: # flatten expiry timestamp
  499. prep["expiry"] = self.expiry.isoformat() + "Z"
  500. # Remove empty entries (those which are None)
  501. prep = {k: v for k, v in prep.items() if v is not None}
  502. # Remove entries that explicitely need to be removed
  503. if strip is not None:
  504. prep = {k: v for k, v in prep.items() if k not in strip}
  505. return json.dumps(prep)
  506. class UserAccessTokenCredentials(credentials.CredentialsWithQuotaProject):
  507. """Access token credentials for user account.
  508. Obtain the access token for a given user account or the current active
  509. user account with the ``gcloud auth print-access-token`` command.
  510. Args:
  511. account (Optional[str]): Account to get the access token for. If not
  512. specified, the current active account will be used.
  513. quota_project_id (Optional[str]): The project ID used for quota
  514. and billing.
  515. """
  516. def __init__(self, account=None, quota_project_id=None):
  517. warnings.warn(
  518. "UserAccessTokenCredentials is deprecated, please use "
  519. "google.oauth2.credentials.Credentials instead. To use "
  520. "that credential type, simply run "
  521. "`gcloud auth application-default login` and let the "
  522. "client libraries pick up the application default credentials."
  523. )
  524. super(UserAccessTokenCredentials, self).__init__()
  525. self._account = account
  526. self._quota_project_id = quota_project_id
  527. def with_account(self, account):
  528. """Create a new instance with the given account.
  529. Args:
  530. account (str): Account to get the access token for.
  531. Returns:
  532. google.oauth2.credentials.UserAccessTokenCredentials: The created
  533. credentials with the given account.
  534. """
  535. return self.__class__(account=account, quota_project_id=self._quota_project_id)
  536. @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
  537. def with_quota_project(self, quota_project_id):
  538. return self.__class__(account=self._account, quota_project_id=quota_project_id)
  539. def refresh(self, request):
  540. """Refreshes the access token.
  541. Args:
  542. request (google.auth.transport.Request): This argument is required
  543. by the base class interface but not used in this implementation,
  544. so just set it to `None`.
  545. Raises:
  546. google.auth.exceptions.UserAccessTokenError: If the access token
  547. refresh failed.
  548. """
  549. self.token = _cloud_sdk.get_auth_access_token(self._account)
  550. @_helpers.copy_docstring(credentials.Credentials)
  551. def before_request(self, request, method, url, headers):
  552. self.refresh(request)
  553. self.apply(headers)