0

I'm trying to make GET request to ("me/todo/lists") endpoint for M365. It works initially after a fresh authentication and acquiring the access-token.

It even works when the access token is saved and the request is made after a couple of minutes, meaning that the code for using the saved access token works.

But when I try to call the API after sometime by storing the access token, I get the error: "Error: Access token has expired or is not yet valid"

Here's the code for making the request with the saved access token

public async getTaskLists(accessToken: string) {
        class MyAuthenticationProvider implements AuthenticationProvider {
            /**
             * This method will get called before every request to the msgraph server
             * This should return a Promise that resolves to an accessToken (in case of success) or rejects with error (in case of failure)
             * Basically this method will contain the implementation for getting and refreshing accessTokens
             */
            public async getAccessToken(): Promise<string> {
                return accessToken;
            }
        }
        const options = {
            authProvider: new MyAuthenticationProvider(), // An instance created from previous step
        };
        const client = Client.initWithMiddleware(options);
    
        //this part fetches task-lists from M365 and populates them into placed in a tree-view using registerTreeDataProvider
    
        let dataObject = [];
        let children: string[] = [];
        try {
            let taskList = await client.api("/me/todo/lists").get();
            console.log(taskList);
            } catch (error) {
            console.log(error);
            }
    }
}

  • The token you get after authenticating the user expires, this is expected behavior. You need to refresh it (or use some library that does it for you). Possible duplicate: https://stackoverflow.com/questions/51153055/how-to-refresh-a-token-for-microsoft-graph – Nikolay Nov 21 '21 at 22:51
  • The token has lifetime of about 60 min. It can't expire right away. There is an issue with Graph API. I started having this issue after I moved from Outlook API to Graph API. – Allen King Jul 24 '23 at 15:08

1 Answers1

0

It is a short-lived access token that is only valid for an hour I think. You need to refresh the token before it expires to be able to make API calls successfully. That means you MUST save the refresh_token in order to do so. refresh_token can be used multiple times from my experiences which is good since it might break the connection if the refresh_token can only be used once and the refresh token response is lost due to network issues. However, it is good practice to save the last refresh_token returned from MS.

Tony Liu
  • 11
  • 1