MSAL access token refreshing intermittently not working through AcquireTokenSilent

Ron Chan 1 Reputation point
2022-05-31T09:37:47.777+00:00

Below is the code used to refresh the token, there are a number of functions that calls this before connecting to Microsoft to get what it needs. Currently there are 3 domains testing this, it works fine for 2 of the domains, however on the 3rd domain, it will periodically stop working. When it does this, it doesn't even run this part of the code. We would add an event in the ms calendar and nothing comes thru from Microsoft, until we get the user to do a manual disconnect and reconnect, then it will work for 24 to 48 hours and stop again

app.post('/token', async (req, res) => {
  const msUserId = req.body.msUserId
  const userId = req.body.userId
  const workspace = req.body.workspace
  const account = await req.app.locals.msalClient.getTokenCache().getAccountByHomeId(msUserId)
  let access_token = 'none'

  if (account) {
    const requestConfig = msConfig.request[project]
    const tokenRequest = { ...requestConfig.tokenRequest, account }
    try {
      // Attempt to get the token silently
      // This method uses the token cache and
      // refreshes expired tokens as needed
      const response = await req.app.locals.msalClient.acquireTokenSilent(tokenRequest)
      access_token = response.accessToken
      console.log('access_token:', account.username, access_token)
    } catch (error) {
      console.error('token error:', account.username, JSON.stringify(error))
      await marKProfileNeedsReconnect(workspace, userId, msUserId)
    }
  }
  res.status(200).json({ access_token })
})
Microsoft Security | Microsoft Entra | Microsoft Entra ID
{count} votes

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.