Skip to content

Refactor proactive refresh logic for better reuse #12601

@chlowell

Description

@chlowell

This logic:

if not token:
  # get new token
elif should_refrsesh:
  try:
     # get new token
  except Exception:
     # swallow

seems to be present in most if not all the credentials. Perhaps it could be moved into a base or mixin, and have the implementation just provide a callback or an override for the # get new token functionality?

Originally posted by @schaabs in #12136

That comment thread also has a sketch of a potential solution:

class CredentialBase(ABC):
    def __init__(self, **kwargs):
        self._client = AadClient(...)

    def _get_token_impl(self, *scopes, **kwargs):
        if not scopes:
            raise ValueError('"get_token" requires at least one scope')

        token = self._client.get_cached_access_token(scopes)
        if not token:
            token = self._request_token(scopes, **kwargs)
        elif self._client.should_refresh(token):
            try:
                self._request_token(scopes, **kwargs)
            except Exception:  # pylint:disable=broad-except
                pass
        return token

    @abc.abstractmethod
    def _request_token(self, *scopes, **kwargs):
        pass

class Credential(CredentialBase):
    def get_token(*scopes, **kwargs):
        """user-facing docstring"""
        return self._get_token_impl(*scopes, **kwargs)

    def _request_token(*scopes, **kwargs):
        """get a new token according to this credential's personal idiom"""
        ...

Metadata

Metadata

Assignees

No one assigned

    Labels

    Azure.IdentityClientThis issue points to a problem in the data-plane of the library.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions