Unable to locate the refresh token with Microsoft Graph

1.4k views Asked by At

I was looking here about refresh tokens.

I have this code to get a access token:

if(bPromptUser)
{
    _AuthResult = await PublicClientApp.AcquireTokenAsync(_scopes); //Opens Microsoft Login Screen

    using (RegistryKey key = Registry.CurrentUser.CreateSubKey(keyName))
    {
        key.OpenSubKey(keyName, true);
        key.SetValue("Status", _AuthResult.AccessToken);
        key.SetValue("Expire", _AuthResult.ExpiresOn.ToLocalTime().ToString());
        key.Close();

        token = _AuthResult.AccessToken;
    }

    // Append the access token to the request.
    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
}

But my _AuthResult doesn't actually have a RefreskToken in the list. Is this because I am using v1 of Microsoft Graph?

Update

According to the documentation the scope suggested in the answer is on by default?

enter image description here

3

There are 3 answers

0
Andrew Truckle On BEST ANSWER

Microsoft provide sample code for TokenCacheHelper.

Add that to your project and provide an instance of it. Then, set the path. Like this:

TokenCacheHelper.CacheFilePath = Program.Options.TokenCachePath;
PublicClientApp = new PublicClientApplication(_AppID, "https://login.microsoftonline.com/common", TokenCacheHelper.GetUserCache());

That is all you need to do. The cache file contains all the token details, including the refresh token.

More details are in the conversation here. In part:

As far as helping you to implement the token cache, to store the content of the token cache, you need to:

  1. Copy the TokenCacheHelper from here to your project.
  2. If you really want to save the content of the cache to the registry, change the implementation of:
    • AfterAccessNotification to write to the registry instead of a file this line
    • BeforeAccessNotification to read fromthe registry instead of a file this line
  3. Construct the PublicClientApplication your as shown here (passing the cache that you get by calling TokenCacheHelper.GetUserCache(): https://github.com/Azure-Samples/active-directory-dotnet-desktop-msgraph-v2/blob/master/active-directory-wpf-msgraph-v2/App.xaml.cs#L19:

    clientApp = new PublicClientApplication(ClientId, "https://login.microsoftonline.com/common", TokenCacheHelper.GetUserCache());

8
Dan Kershaw - MSFT On

I believe when using MSAL (and the v2 auth endpoint) that you don't get a refresh token by default. To get the refresh token you need to request the offline_access scope as well as the other scopes. Please see https://developer.microsoft.com/en-us/graph/docs/concepts/permissions_reference#openid-permissions for more details.

Hope this helps,

0
Jacob Sharp On

For me, my problem was using an older version of the Microsoft.Identity.Client nuget package. Upgrading from 4.35.1 to 4.40.0 fixed the token error.