There are two ways to deal with this (at least this is how we do it in our application, it would be interesting to find out what the AD gurus say about it, so that we can also fix it if this is not the right way to do something- then):
General Approach - Use Update Token
When you get an access token from AD, today you get 3 points ago - an access token, access to a token and an update token. What you do is cache all three of them in your application. Until the access token expires, you can simply use this access token. After the token has expired, you can use the update token to get a new access token. The method in ADAL that you want to use for this purpose is AcquireTokenByRefreshToken .
Having said that , you should not accept a hard dependency in your application in the update token . Based on the best practices described here , the update token may expire or be canceled. In addition, based on the Vittorio post update token is not returned even in the ADAL 3 version. So you can think about it.
Another approach is silent use of a token
Another approach you could take is to get the new token quietly on behalf of the user after the token expires. I believe this requires that the user must manually log in at least once in your application and follow the OAuth2 stream. The method you want to use is AcquireTokenSilent .
Here's the pseudo code for our approach:
var now = DateTime.UtcNow.Ticks; if (now <= tokenExpiry && !string.IsNullOrWhiteSpace(accessToken)) return accessToken; var clientCredential = new ClientCredential(ClientId, ClientSecret); var authContext = new AuthenticationContext(string.Format("{0}/{1}", AzureActiveDirectorySignInEndpoint, azureADTenantId)); AuthenticationResult authResult = null; if (!string.IsNullOrWhiteSpace(refreshToken)) { authResult = await authContext.AcquireTokenByRefreshTokenAsync(refreshToken, clientCredential, ADEndpoint); } else { authResult = await authContext.AcquireTokenSilentAsync(Endpoint, clientCredential, new UserIdentifier(userId, UserIdentifierType.UniqueId)); } return authResult.AccessToken;
Gaurav mantri
source share