How to renew Jwt Access tokens using refresh tokens

Mayuri Barve 1 Reputation point
2022-01-19T19:27:06.173+00:00

Hello,

I am developing an application- Web app and Web Api using .Net Core 5.0 and MVC. I have implemented API Authorization in the application to secure my Web API using JWT access token. I referred to this link to implement this on behalf of the signed in user from my web application.
https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-protected-web-api-app-configuration?view=aspnetcore-5.0

I am getting Jwt Bearer access token in my web app using ITokenAcquisition service as tokenAcquisition.GetAccessTokenForUserAsync(scopes) and passing it in authorization header in the request. Have used [RequiredScope(RequiredScopesConfigurationKey = "AzureAd:Scopes")] at Api Controller level in Web API. Also have done few changes in Startup -> ConfigureServices method with the help of link, that's it. API Authorization is working fine.. I am able to access endpoints with valid Jwt token and unable to access without it in postman.

But issue is this Jwt token is getting expired after certain time like 90 minutes in my app I think and API returns UnAuthorized 404 response. How can I avoid this? How to get refresh token? What configurations I need to do in app to use refresh token when access token expires? What is the default expiration time for jwt access token. How do i change it?

Am I following/using the correct link above/approach for API Authorization? Am I missing anything in this?

Please suggest as my release is stuck because of this one issue of expired tokens. If anyone could share sample code, approach at the earliest that will be really helpful.

Thanks.

Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
8,216 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
22,997 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. AmanpreetSingh-MSFT 56,731 Reputation points
    2022-01-20T11:17:34.957+00:00

    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.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.