Thursday, 16 November 2023

Microsoft Graph token expiring after 1 day

I'm trying to integrate Microsoft token into my app, but I have a weird bug where even if I'm refreshing the token every 30 min, it says that the token has expired after 1 day. I'm getting the token from the user with the following code

const scope = e.target.dataset.scope;
var url = new URL("https://login.microsoftonline.com/common/oauth2/v2.0/authorize")
const params = {
  client_id: '****',
  response_type: 'code',
  redirect_uri: `${Meteor.settings.public.__BASE_URL}/template/email-import`,
  scope: 'user.read mail.read mail.readbasic mail.readwrite Mail.Send',
  code_challenge: '****',
  code_challenge_method: 'plain',
  state: scope
}
        
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
window.location.replace(url);

And after that I catch the response with the access token and the refresh token and it gets refreshed every 30 min with the following code

const params = {
  client_id: '****',
  scope: 'user.read mail.read mail.readbasic mail.readwrite Mail.Send',
  redirect_uri: Meteor.settings.public.__JTI_SERVER + '/template/email-import', 
  grant_type: 'refresh_token',
  refresh_token: refreshToken,
}
var formData = new URLSearchParams();
for (var k in params) {
  formData.append(k, params[k]);
}
const response = await fetch('https://login.microsoftonline.com/common/oauth2/v2.0/token', {
  method: 'POST',
  body: formData,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Origin': Meteor.settings.public.__JTI_SERVER + '/template/email-import'
  }
})
const json = await response.json();
if(json.error) {
  throw new Error(`Error refreshing the token for company id ${company._id} and email ${company.email_details[scope].user_info.mail}`)
} else {
  Company.update(company._id, {$set: {[`email_details.${scope}.microsoft_token`]: json }})
}

I honestly think that I'm refreshing the token correctly as I get a different access and refresh token each time the function runs. But even with that the token seems to expire after a day and I cannot find in the settings where to change this.

The complete error log I'm getting is

{
error: 'invalid_grant',
error_description: 'AADSTS700081: The refresh token has expired due to maximum lifetime. The token was issued on 2021-05-23T09:51:53.7700436+00:00 and the maximum allowed lifetime for this application is 1.00:00:00.\r\n' +
'Trace ID: e0ae3ecc-1324-4ae5-823b-ed38e393a400\r\n' +
'Correlation ID: 409fd9ed-64c0-4f81-8ba7-546e6ceb2542\r\n' +
'Timestamp: 2021-05-26 07:30:01Z',
error_codes: [ 700081 ],
timestamp: '2021-05-26 07:30:01Z',
trace_id: 'e0ae3ecc-1324-4ae5-823b-ed38e393a400',
correlation_id: '409fd9ed-64c0-4f81-8ba7-546e6ceb2542',
error_uri: 'https://login.microsoftonline.com/error?code=700081'
}

If someone could help with this it would be very appreciated.

Thanks in advance,

Oscar



from Microsoft Graph token expiring after 1 day

No comments:

Post a Comment