Hi @Mayuri Barve • Thank you for reaching out.
When you acquire an access token using the Microsoft Authentication Library for .NET (MSAL.NET), the token is cached. When the application needs a token, it should first call the AcquireTokenSilent method to verify if an acceptable token is in the cache. In many cases, it's possible to acquire another token with more scopes based on a token in the cache. It's also possible to refresh a token when it's getting close to expiration (as the token cache also contains a refresh token).
var accounts = await app.GetAccountsAsync();
AuthenticationResult result = null;
try
{
result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
.ExecuteAsync();
}
catch (MsalUiRequiredException ex)
{
// A MsalUiRequiredException happened on AcquireTokenSilent.
// This indicates you need to call AcquireTokenInteractive to acquire a token
Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");
try
{
result = await app.AcquireTokenInteractive(scopes)
.ExecuteAsync();
}
catch (MsalException msalex)
{
ResultText.Text = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
}
}
catch (Exception ex)
{
ResultText.Text = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
return;
}
if (result != null)
{
string accessToken = result.AccessToken;
// Use the token
}
For Web applications that use OpenID Connect Authorization Code flow, the recommended pattern in the Controllers is to:
- instantiate a ConfidentialClientApplication with a token cache for which you would have customized the serialization See token cache serialization for Web apps
- Call AcquireTokenByAuthorizationCode
Then in the web app, each time you want to get a token for an API, just call AcquireTokenSilent. If AcquireTokenSilent throws an MsalUiRequiredException, then the web API will need to challenge the user.
What is the default expiration time for jwt access token. How do i change it?
Access token is by default valid for 1 Hour and can be configured to Minimum 10 minutes and Maximum 1 day. To change the token lifetime, you need to use Azure AD Policy as mentioned here: https://learn.microsoft.com/en-us/azure/active-directory/develop/configure-token-lifetimes#create-a-policy-for-web-sign-in
-----------------------------------------------------------------------------------------------------------
Please "Accept the answer" if the information helped you. This will help us and others in the community as well.