Skip to content

Microsoft.Graph.ServiceException: Code: InvalidAuthenticationToken Message: ArgumentNull when creating Outlook subscription or getting outlook message #2883

@cong-carepatron

Description

@cong-carepatron

Describe the bug

We have developed our application (creating an Azure app) that will connected to the office 360 accounts (Outlook) of our clients to sync Outlook messages and calendar of our clients

Our scope: profile email openid Mail.ReadWrite Mail.Read Mail.Send Mail.ReadBasic Calendars.ReadWrite

It works well for most of our clients except one of our client, they often get this error and it is very distracted because they have to re-login again.

Our code snipe implementation:

`
var httpClient = httpClientFactory.CreateClient(OutlookHttpClient);

        httpClient.DefaultRequestHeaders.Add("Prefer", "IdType=\"ImmutableId\"");

        graphClient = new GraphServiceClient(httpClient)
        {
            AuthenticationProvider = authenticationProvider
        };

return await graphClient.Me.Messages[messageId].Request().Expand("attachments").GetAsync();` to get their message

This is some of our requests. I hope it could help to debug/troubleshoot our problem.

Inner error: AdditionalData: date: 2025-04-08T21:47:33 request-id: 91b76e1c-04cd-4c14-a37c-a3b9cf0d193b client-request-id: 91b76e1c-04cd-4c14-a37c-a3b9cf0d193b ClientRequestId: 91b76e1c-04cd-4c14-a37c-a3b9cf0d

`Error while calling external service - MsOutlook - error: Code: InvalidAuthenticationToken
Message: ArgumentNull
Inner error:
AdditionalData:
date: 2025-04-08T22:35:28
request-id: 0f037953-5b07-4bb8-9d98-135608856ae3
client-request-id: 0f037953-5b07-4bb8-9d98-135608856ae3
ClientRequestId: 0f037953-5b07-4bb8-9d98-135608856ae3

  • Scope: Calendars.ReadWrite Calendars.ReadWrite.Shared email Mail.Read Mail.ReadBasic Mail.ReadWrite Mail.ReadWrite.Shared Mail.Send openid profile`

Expected behavior

The messages should be returned normally.

How to reproduce

Connected the app & granted the permissions. It works well for some hours or some days.
Suddenly, the Outlook server denied the request.

Althought we implement the auto referesh

public class MicrosoftAuthenticationProvider : IAuthenticationProvider
{
private readonly ConnectedApp connectedApp;
private readonly CalendarConfig calendarConfig;

    public MicrosoftAuthenticationProvider(CalendarConfig calendarConfig, ConnectedApp connectedApp)
    {
        this.connectedApp = connectedApp;
        this.calendarConfig = calendarConfig;
    }

    public async Task AuthenticateRequestAsync(HttpRequestMessage request)
    {
        // if it expires in the next 10 mins
        if (connectedApp.ExpiresUtc.ToUniversalTime() <= DateTime.UtcNow.AddMinutes(10))
        {
            using (var client = new HttpClient()
            {
                BaseAddress = new Uri(calendarConfig.MicrosoftAuthUri)
            })
            {
                var dict = new Dictionary<string, string>
                {
                    { "client_id", calendarConfig.MicrosoftClientId },
                    { "client_secret", calendarConfig.MicrosoftClientSecret },
                    { "grant_type", "refresh_token" },
                    { "refresh_token", connectedApp.RefreshToken },
                    { "scope", connectedApp.Scope },
                    { "redirect_uri", calendarConfig.RedirectUri },
                };

                var refreshRequest = new HttpRequestMessage
                {
                    Method = HttpMethod.Post,
                    Content = new FormUrlEncodedContent(dict)
                };
                refreshRequest.Headers.Add("Accept", "application/json");

                using (var response = await client.SendAsync(refreshRequest))
                {
                    var result = await response.Content.ReadAsAsync<OAuthResponse>();

                    connectedApp.AccessToken = result.access_token;
                    connectedApp.ExpiresUtc = DateTime.UtcNow.AddSeconds(result.expires_in);
                }
            }
        }

        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", connectedApp.AccessToken);
    }
}

And we renew the token every day.

SDK Version

4.3.0

Latest version known to work for scenario above?

No response

Known Workarounds

No response

Debug output

Click to expand log ```
</details>


### Configuration

_No response_

### Other information

_No response_

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions