ab.it.gcp
ab.it.gcp

Reputation: 334

Error while fetching refresh token from Azure AD

I am trying to get refresh token from azure AD but getting this error :-

data {"error":"invalid_grant","error_description":"AADSTS9002313: Invalid request. Request is malformed or invalid.\r\nTrace ID: 4bcb6e5e-35c1-4c4e-b184-d0ffddcc6301\r\nCorrelation ID: 689f7abd-13ef-41f9-b94a-4b2269bb7c32\r\nTimestamp: 2023-03-03 11:15:39Z","error_codes":[9002313],"timestamp":"2023-03-03 11:15:39Z","trace_id":"4bcb6e5e-35c1-4c4e-b184-d0ffddcc6301","correlation_id":"689f7abd-13ef-41f9-b94a-4b2269bb7c32","error_uri":"https://login.microsoftonline.com/error?code=9002313"}

Code:

const http = require('http');
const url = require('url');
const hostname = '127.0.0.1';
const port = 3000;


const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');


    let reqUrl = req.url;
   let code1 = reqUrl.substring(reqUrl.indexOf("?code=") + 6, reqUrl.length);
   let code=code1.split('&')[0];

        // const tokenEndpoint = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
        const clientId = <client id>;
        const redirectUri = 'http://localhost:3000/callback'; // The URL to redirect to after login
        const grantType = 'authorization_code';
        const clientSecret = <client secret>;
        
        
        const tokenRequest = {
          method: 'POST',
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
          body: `grant_type=${grantType}&code=${code}&redirect_uri=${redirectUri}&client_id=${clientId}&client_secret=${clientSecret}`
        };

    let refreshToken;   
  
  fetch(tokenEndpoint, tokenRequest)
  .then(response => response.json())
  .then(data => {
    refreshToken = data.refresh_token;
    // Use the refresh token to request new access tokens as needed
  })
  .catch(error => {
    // Handle error
res.end('error');
  });

  res.end(refreshToken);
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Upvotes: 0

Views: 1336

Answers (1)

Sridevi
Sridevi

Reputation: 22317

I tried to reproduce the same in my environment and got below results:

I registered one Azure AD application and added API permissions as below:

enter image description here

When I ran same code as you to get refresh token, I got similar error like below:

const http = require('http');
const url = require('url');
const hostname = '127.0.0.1';
const port = 3000;


const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');


    let reqUrl = req.url;
   let code1 = reqUrl.substring(reqUrl.indexOf("?code=") + 6, reqUrl.length);
   let code=code1.split('&')[0];

        const tokenEndpoint = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
        const clientId = <client id>;
        const redirectUri = 'http://localhost:3000/callback'; // The URL to redirect to after login
        const grantType = 'authorization_code';
        const clientSecret = <client secret>;
        
        
        const tokenRequest = {
          method: 'POST',
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
          body: `grant_type=${grantType}&code=${code}&redirect_uri=${redirectUri}&client_id=${clientId}&client_secret=${clientSecret}`
        };

    let refreshToken;   
  
  fetch(tokenEndpoint, tokenRequest)
  .then(response => response.json())
  .then(data => {
    refreshToken = data.refresh_token;
    // Use the refresh token to request new access tokens as needed
  })
  .catch(error => {
    // Handle error
res.end('error');
  });

  res.end(refreshToken);
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Response:

enter image description here

To resolve the error, I generated code value explicitly and included it as a parameter in variable while fetching token.

I ran below authorization request in browser and got code value in address bar like this:

https://login.microsoftonline.com/common/oauth2/v2.0/authorize? 
client_id=<appID>
&response_type=code  
&redirect_uri=http://localhost:3000/callback
&response_mode=query  
&scope= https://graph.microsoft.com/.default 
&state=12345

Response:

enter image description here

Make sure to pass offline_access in scope parameter while generating refresh token.

Now, I ran below modified code and got refresh token successfully in output like below:

const axios = require('axios');
const qs = require('qs');

const TENANT_ID = 'common';
const CLIENT_ID = 'a3bebc65-2ba6-4f07-b633-xxxxxxxxxx';
const CLIENT_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx';
const AUTHORIZATION_CODE = 'paste_code_from_above_request';
const REDIRECT_URI = 'http://localhost:3000/callback';
const SCOPE = 'https://graph.microsoft.com/.default offline_access';

const TOKEN_ENDPOINT = `https://login.microsoftonline.com/${TENANT_ID}/oauth2/v2.0/token`;

const requestBody = qs.stringify({
  code: AUTHORIZATION_CODE,
  client_id: CLIENT_ID,
  client_secret: CLIENT_SECRET,
  redirect_uri: REDIRECT_URI,
  scope: SCOPE,
  grant_type: 'authorization_code'
});

axios.post(TOKEN_ENDPOINT, requestBody, {
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})
  .then(response => {
    console.log(response.data.refresh_token);
  })
  .catch(error => {
    console.error(error);
  });

Response:

enter image description here

To confirm that, I included above refresh token in below parameters via Postman and got access token successfully like this:

POST https://login.microsoftonline.com/common/oauth2/v2.0/token
client_id:<appID>
grant_type:refresh_token
scope: https://graph.microsoft.com/.default
redirect_uri: http://localhost:3000/callback
client_secret: <secret>
refresh_token: <paste_refresh_token_from_above_code_output>

Response:

enter image description here

Upvotes: 1

Related Questions