How to refresh a token for Microsoft Graph

Hugo Hilário picture Hugo Hilário · Jul 3, 2018 · Viewed 9.1k times · Source

I'm connecting to the Microsoft Graph using:

public GraphServiceClient GetAuthenticatedClient(string token)
{
    GraphServiceClient graphClient = new GraphServiceClient(
        new DelegateAuthenticationProvider(
            async (requestMessage) =>
            {
                // Append the access token to the request.
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
            }));
    return graphClient;
}

I'm running this code on the server. The token I'm using is being sent to me by an external App.

Everything works great during the first hour, then the token expires.

My question is : How can I get a new token, since I also have access to the refresh token?

Answer

Marc LaFleur picture Marc LaFleur · Jul 3, 2018

There are two pieces required to enable Refresh Tokens:

  1. You need to request the scope offline_access. This tells the endpoint to provide a refresh_token alongside the access_token and associated metadata.

  2. You need to request a new access_token (and refresh_token as they come together) by repeating the same POST to /common/oauth2/v2.0/token with a slightly different body - grant_type is set to refresh_token and instead of a code, you supply a refresh_token property and value:

    https://login.microsoftonline.com/common/oauth2/v2.0/token
    Content-Type: application/x-www-form-urlencoded
    
    grant_type=refresh_token&
    refresh_token=[REFRESH TOKEN]&
    client_id=[APPLICATION ID]&
    client_secret=[PASSWORD]&
    scope=[SCOPE]&
    redirect_uri=[REDIRECT URI]
    

A while back I wrote up a show primer on the v2 Endpoint that you might find helpful as well.