Search code examples
asp.net-coreazure-active-directorymicrosoft-graph-apiblazor-server-sidemicrosoft-identity-platform

Microsoft Identity - how to check access token validity and prevent MsalUiRequiredException


I have a Blazor Server app that calls downstream api (Sharepoint Online API) on behalf of logged in user.

However, users are sometimes getting MsalUiRequiredException. I understand that's because the token became invalid.

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)                   
   .AddMicrosoftIdentityWebApp(configuration.GetSection("AzureAd"))
   .EnableTokenAcquisitionToCallDownstreamApi(sharepointScopes)
   .AddDistributedTokenCaches();

ClientContext SharepointClientFactory()
{
   var clientContext = new ClientContext(siteUrl);

   clientContext.ExecutingWebRequest += (sender, e) =>
   {
       try
       {
           string accessToken = _tokenAcquisition
                           .GetAccessTokenForUserAsync(scopes: effectiveScopes, authenticationScheme: OpenIdConnectDefaults.AuthenticationScheme)
                           .GetAwaiter()
                           .GetResult();

           e.WebRequestExecutor.RequestHeaders.Add("Authorization", $"Bearer {accessToken}");
       }
       catch (MicrosoftIdentityWebChallengeUserException ex)
       {
           //_consentHandler.HandleException(ex); I want prevent this from happening in advance
       }
   };
}

Simple page refresh does not help here, because the authentication cookie is still valid.

  1. How do I check the access token validity before the app is shown to the user? (e.g. when user visits _host.cshtml which hosts the blazor app)?

  2. Is there any other way to prevent access token expiration during user session?


Solution

  • you can use this to check access token validity

    public async Task<bool> IsAccessTokenValid()
    {
        try
        {
            string accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(scopes: effectiveScopes, authenticationScheme: OpenIdConnectDefaults.AuthenticationScheme);
            return true;
        }
        catch (MicrosoftIdentityWebChallengeUserException ex)
        {
            // Access token is invalid
            return false;
        }
    }