Cloud Developer: Office 365 REST API returns 401 access denied with an error code of “invalid_token”

In recent times i worked with this cloud developer (Azure AD, Office 365 REST API) where they created a custom application. It uses (Calendar, Contact, Mail APIs) to pull items from the specified user mailbox. Intermittently they see “401 Access Denied” followed by error code “invalid_token” from the API. During the investigation, we noticed that after 60 minutes the access token becomes invalid.

Native Application to Web API Diagram

So we recommended them to follow the pattern to cache the access token and use it to call the APIs until it return 401. When they get the 401 event, their app should use the refresh token to get a new access token and retry the request. It worked like a charm for the customer.

Note: When the access token expires, the client application will receive an error that indicates the user needs to authenticate again. If the application has a valid refresh token, it can be used to acquire a new access token without prompting the user to sign in again. If the refresh token expires, the application will need to interactively authenticate the user once again. You can refer: https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-authentication-scenarios

Hope this helps.