Search code examples
c#oauth-2.0microsoft-graph-apiazure-identity

How to manage tokens and refresh tokens on Azure.Identity with authorization code flow?


I am confused on how to use authorization code flow using the Azure.Identity library. Here is a code sample taken from there site (https://github.com/microsoftgraph/msgraph-sdk-dotnet/blob/dev/docs/tokencredentials.md).

string[] scopes = {"User.Read"};
AuthorizationCodeCredential authorizationCodeCredential = new AuthorizationCodeCredential(tenantId, clientId,  clientSecret, authCode);
GraphServiceClient graphClient = new GraphServiceClient(authorizationCodeCredential, scopes);
User me = await graphClient.Me.Request()
                .GetAsync();

The problem is the generated token and refresh token are completely hidden so it can't be reused on future requests. Running this exact code again yields an error because auth codes cannot be used twice. My questions are:

  • The code above shows how to generate a token based on the provided auth code. How can I reuse this token for future transactions without providing another auth code?
  • If the token expires, how to refresh the token? The docs does not talk about this at all.

Solution

  • The AuthorizationCodeCredential class handles the tokens for you. You should reuse the instance of the class once instantiated with the authCode the first time.