GraphServiceClient using authorization token / refresh token mechanism

104 Views Asked by At

In my current application, I have created a refresh token / access token pair based on an authentication code I sent to my user. I continuously refresh this token (using said refresh token) to guarantee its integrity. When working directly with msal, I would get this token and pass it directly in the headers of my HTTP requests. I'm now migrating over to using the msgraph python sdk, and I cannot find a way of achieving this same flow using azure.identity in order to create a GraphServiceClient and make my requests.

I have at my disposal both the refresh and the access token, as well as the client id and secret.

1

There are 1 best solutions below

0
Demian Licht On BEST ANSWER

Ok so I ended up doing something fairly naive, but it works. YMMV though. Also of important consideration, this application works on delegated permissions, so no ClientSecretCredentials for me. I ended up creating something akin to:

class RawAccessTokenProvider:
    """
    A simple credential provider that returns a raw access token for use with Azure SDK clients.
    """

    def __init__(self, access_token: str, expires_on: int) -> None:
        self._access_token = access_token
        self._expires_on = expires_on

    def get_token(self, *scopes, **kwargs) -> AccessToken:
        return AccessToken(self._access_token, self._expires_on)

and using it like so:

    def get_client_by_token_credential(self, token, expires_on) -> GraphServiceClient:
        credentials = RawAccessTokenProvider(token, expires_on)
        return GraphServiceClient(credentials=credentials)

All the credit goes to the answer here.