Ahmad Rehman
Ahmad Rehman

Reputation: 22

Request Azure OAuth 2.0 Token unable to generate

I am trying to generate access token by hitting the following link:

       {https://login.microsoftonline.com/xxxxxx-def2-4558-93fc-9b8f44aaf78a/oauth2/v2.0/authorize?
       client_id=xxxxxx-xxxx-xxxxx-8f83-f5dc90ec4f74
       &response_type=code
       &redirect_uri=https://xxxx-xxxxx.azurewebsites.net/api/HttpTrigger2
       &response_mode=query
       &scope=User.Read
       &state=12345
     &code_challenge=YTFjNjI1OWYzMzA3MTI4ZDY2Njg5M2RkNmVjNDE5YmEyZGRhOGYyM2IzNjdmZWFhMTQ1ODg3NDcxY2Nl
      &code_challenge_method=plain

}

but in a response i got request code instead of token. i am using the following Code in HTTP Trigger

  var resultcode;
  module.exports=async function(context,req){ 
  context.log('JavaScript HTTP trigger function processed a request.');
  const code = (req.query.code || (req.code && req.body.code));
  resultcode=code;
  context.res = generatetoken(context,resultcode);
  context.done();
     }
  function generatetoken(context,rescode){
  var request = require('request');
  var options = {
  'method': 'POST',
  'url': 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
  'headers': {
  'Content-Type': 'application/x-www-url-form-urlencoded'
  },
  form: {
 'client_id': '79c9a036-42e5-407d-8f83-f5dc90ec4f74',
 'code': rescode,
 'redirect_uri': 'http://localhost/myapp/',
 'grant_type': 'Authorization_Code',
 'client_secret': 'W-ie3QlV-_O084H.0U8R2E3bfr_Aun5j_T'
  }
  };
 request(options, function (error, response) {
 if (error) throw new Error(error);
 console.log("response.body");
 context.res={
  body:response
 }
 });
 }

Upvotes: 0

Views: 121

Answers (2)

Ahmad Rehman
Ahmad Rehman

Reputation: 22

i resolved this issue by the following method 1.create a HTTP Trigger function and generate token silently. by posting the following request

https://login.microsoftonline.com/xxxxxxx-xxxx-4558-xxxx- 
xxxxxxxxx/oauth2/v2.0/authorize?
client_id=79c9xxxx-xxxx-xxxx-xxxx-f5dc90ec4f74
&response_type=token
&redirect_uri=https://xxxx-client.azurewebsites.net/api/HttpTrigger2
&response_mode=fragment
&scope=User.Read
&state=12345
&code_challenge=YTFjNjI1OWYzMzA3MTI4ZDY2Njg5M2RkNmVjNDE5YmEyZGRhOGY
yM2IzNjdmZWFhMTQ1ODg3NDcxY2Nl
&code_challenge_method=plain

and the following below function:

   module.exports=async function(context,req){ 
   context.log('JavaScript HTTP trigger function processed a request.');
   const code = (req.query.code || (req.code && req.body.code));
   context.res= {
   body:code  
  };
    }

Upvotes: 0

Hury Shen
Hury Shen

Reputation: 15724

It seems you use Auth code grant flow to get the access token. The steps of Auth code grant flow is request an authorization code first, and then request for the access token.

First step: Request an authorization code is what you did with the link you provided at the beginning of your question. It will redirect to a url with with "code=xxxxx". You need to get the code.

Next step: Request for access token with the code which you got above. Please refer to the screenshot below, the screenshot is what I request for access token with "code". You just need to implement the request below in your function code. enter image description here

==================================Update===========================

Below is my function code for your reference:

module.exports = async function (context, req) {
    var resultcode;
    resultcode="0.ARoATqxxxxxxxxxxVtwgAA";
    context.res = generatetoken(context,resultcode);
    context.res = {
        body: "success"
    };
}

function generatetoken(context,rescode){
    var request = require('request');
    var options = {
    'method': 'POST',
    'url': 'https://login.microsoftonline.com/e4c9xxxxxxxxba2a757fb/oauth2/v2.0/token',
    'headers': {
    'Content-Type': 'application/x-www-url-form-urlencoded'
    },
    form: {
   'client_id': '7a6f7xxxxxxxxxxfd79e9',
   'code': rescode,
   'redirect_uri': 'https://hurytest',
   'grant_type': 'Authorization_Code',
   'scope': 'openid https://graph.microsoft.com/.default',
   'client_secret': '2Wjp2xxxxxxxxxxxxXdq4Qckdi'
    }
    };
   request(options, function (error, response) {
    if (error) throw new Error(error);
    console.log(response.body);
    context.res={
        body:response
    }
   });
}

The code above can console the access token success as below screenshot show: enter image description here

=============================Update 2======================

If you want the token shown in the response of the function, please refer to my code:

module.exports = async function (context, req) {
    var resultcode;
    resultcode="0.ARoATqvJ5Cxxxxxxxxxxv5wiH9RSQ0gAA";
    var result = await generatetoken(context,resultcode);
    context.res = {
        body: result
    };
}

function generatetoken(context,rescode){
    var request = require('request');
   
    var options = {
    'method': 'POST',
    'url': 'https://login.microsoftonline.com/e4c9xxxxxxxxxxxx57fb/oauth2/v2.0/token',
    'headers': {
    'Content-Type': 'application/x-www-url-form-urlencoded'
    },
    form: {
   'client_id': '7a6fxxxxxxxxxxxxxfd79e9',
   'code': rescode,
   'redirect_uri': 'https://hurytest',
   'grant_type': 'Authorization_Code',
   'scope': 'openid https://graph.microsoft.com/.default',
   'client_secret': '2WjpxxxxxxxxxxxQckdi'
    }
    };
    return new Promise(function(resolve, reject) {
        request(options, function(err, res) {
            if (err) {
            reject(err);
            } else {
            resolve(res.body);
            }
        })
    })
}

Upvotes: 1

Related Questions