how can I get refresh token

12,508

Solution 1

The acquiretokenbyrefreshtoken function is available in ADAL 2.X , that code sample is using ADAL 3.13.8 , and from ADAL3.X, library won't expose refresh token and AuthenticationContext.AcquireTokenByRefreshToken function.

ADAL caches refresh token and will automatically use it whenever you call AcquireToken and the requested token need renewing(even you want to get new access token for different resource).

please see the explanation from here . Also click here and here for more details about refresh token in ADAL .

Solution 2

If you looking for a persistent mechanism, you can simply use TokenCache.Serialize()

Here's how I did it:

First, get the token and serialize the cache token

AuthenticationContext authContext = new AuthenticationContext($"https://login.microsoftonline.com/{Tenant}");
var authResult = authContext.AcquireTokenAsync(resource, ClientId, new Uri("https://login.microsoftonline.com/common/oauth2/nativeclient"), new PlatformParameters(PromptBehavior.SelectAccount)).Result;
byte[] blobAuth = authContext.TokenCache.Serialize();

Then, load the cached bytes

AuthenticationContext authContext = new AuthenticationContext($"https://login.microsoftonline.com/{tenant}/");
authContext.TokenCache.Deserialize(blobAuth);
var res = authContext.AcquireTokenSilentAsync(resource, clientId).Result;
Share:
12,508

Related videos on Youtube

Phoenix
Author by

Phoenix

Updated on June 04, 2022

Comments

  • Phoenix
    Phoenix almost 2 years

    i learn this code sample :https://github.com/Azure-Samples/active-directory-dotnet-graphapi-web ,and yes ,i can get access token in AuthorizationCodeReceived : AuthenticationHelper.token = result.AccessToken;

    but how do i get the refresh token ?result.RefreshToken is not available , then how do i use acquiretokenbyrefreshtoken function ?

    https://msdn.microsoft.com/en-us/library/microsoft.identitymodel.clients.activedirectory.authenticationcontext.acquiretokenbyrefreshtoken.aspx

  • Phoenix
    Phoenix about 7 years
  • Neo
    Neo over 5 years
    but what about AcquireTokenSilentAsync ? it is also throwing exception fail to acquire token even if cache is match
  • Meir
    Meir over 4 years
    There's no need to have access to the refresh token if the class refreshes it for you. So you just need to keep a copy of the object around, serialized like this answer shows. Useful answer, thanks!
  • Yinon_90
    Yinon_90 over 4 years
    Definitely right, as long as the object in memory you can use the "AcquireTokenSilentAsync" function that does the refresh without Serialize, but then every time you restart the program you will have to request the Access Token again. My answer here is to show how to manage persistence token that can also be saved in DB \ File