'How to refresh token for GraphServiceClient

I have the following code:

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(config.GetSection("AzureAd"))
    .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
    .AddMicrosoftGraph(config.GetSection("DownstreamApi"))
    .AddInMemoryTokenCaches();

I get GraphServiceClient using DI:

    private readonly GraphServiceClient _graphServiceClient;
    public MailsRangeModel(GraphServiceClient graphServiceClient)
    {
        _graphServiceClient = graphServiceClient;
    }

then I try to call

await _graphServiceClient.Me.MailFolders[folderId].Messages

I get the following error when token is expired:

ServiceException: Code: InvalidAuthenticationToken Message: Access token has expired or is not yet valid.

I know about ability to change token lifecycle on Active Directory, but I don't have access to it.

I just want to get new token instead of show this exception to client.

How to do it?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source