2

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?

Oleg Sh
  • 8,496
  • 17
  • 89
  • 159
  • You should send one additional `POST` request for getting `refresh token` you could [`have a look here in official document`](https://learn.microsoft.com/en-us/graph/auth-v2-user#5-use-the-refresh-token-to-get-a-new-access-token) – Md Farid Uddin Kiron May 18 '22 at 06:27
  • In addition, may we know which `auth protocol` you are using to get access token? – Md Farid Uddin Kiron May 18 '22 at 06:33
  • I don't think that this line "await _graphServiceClient.Me.MailFolders[folderId].Messages" will work. It should be something like this "var messages = await _graphServiceClient.Me.MailFolders[folderId].Messages.Request().GetAsync();" – user2250152 May 18 '22 at 06:35

0 Answers0