首页 > 解决方案 > NodeJS web app access Azure REST API Authentication fails

问题描述

I am trying to create a sample NodeJS App where I will be calling Azure Log Analytics REST API and I have App Registration already done but I am not a Node JS developer and unfortunately stuck here, I got some code from some searching around but this doesnt work at all, can someone help me how I can get this to get Authentication token from NodeJs (I just created a sample Express NodeJs app and pasted the below code) but its not working, if someone can help me with fixing the code:

var express = require('express');
const axios = require('axios');
const qs = require('qs');
const APP_ID = 'XXXXXXXXXXXXXXXXXXX';
const APP_SECERET = 'YYYYYYYYYYYYYYYYY';
const TOKEN_ENDPOINT ='https://login.microsoftonline.com/MYTENANTID/oauth2/v2.0/token';
const MS_GRAPH_SCOPE = 'Data.Read';
const resource ='GUID FOR LOG ANALYTICS WORKSPACE';
var responseval = "";


const postData = {
  client_id: APP_ID,
  scope: MS_GRAPH_SCOPE,
  client_secret: APP_SECERET,
  grant_type: 'client_credentials',
  resource: resource
};

axios.defaults.headers.post['Content-Type'] =
  'application/x-www-form-urlencoded';

let token = '';

axios
  .post(TOKEN_ENDPOINT, qs.stringify(postData))
  .then(response => {
    console.log(response.data);
    responseval = response.data;
  })
  .catch(error => {
    console.log(error);
    responseval = error;
  });

var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express ' + responseval });
});

module.exports = router;

Following is my WORKING POWERSHELL CODE which I am trying to get working in NODE.Js

$tenantId      = "MYTENANT ID"  #Directory ID for THREE PROJECT





$formData = @{

  client_id = "XXXXXXXXXXXXXX";

  client_secret = "YYYYYYYYYYYYYYYYYYYY";

  scope = 'Data.Read';

  grant_type = 'client_credentials';

  resource = 'https://api.loganalytics.io'

}


$uri = 'https://login.microsoftonline.com/' + $tenantId + '/oauth2/token?api-version=1.0'
$response = Invoke-RestMethod -Uri $uri -Method Post -Body $formData -ContentType "application/x-www-form-urlencoded"

$authHeader = @{

'Content-Type'='application/json'

'Authorization'= 'Bearer ' + $response.access_token

}

$request1 = "https://api.loganalytics.io/v1/workspaces/LOGANALYTICS WORKSPACE ID/query?query=externalapistatus_CL "

$resultz1 = Invoke-RestMethod -Uri $request1 `

                  -Headers $authHeader `

                  -Method Get

标签: node.jsoauth-2.0azure-active-directory

解决方案


在收集了一些小的基础知识之后,感谢 Node.JsTutorial by Programming with @Mosh(Youtube Node.Js 基础教程),我能够得到这个工作。我按照上面@Gary 的建议构建了一个简单的控制台Node.Js 应用程序,下面是现在返回令牌的代码(下一步将把它放入函数中并在web-App 中使用它):-

const axios = require('axios');
const oauth = require('axios-oauth-client');
const qs = require('qs');
const APP_ID = 'XXXXXXXXXXXXXXXX';
const APP_SECERET = 'YYYYYYYYYYYYYYYY';
const TOKEN_ENDPOINT ='https://login.microsoftonline.com/MyTenantID/oauth2/token?api-version=1.0';
const MS_GRAPH_SCOPE = 'Data.Read';
const resource ='https://api.loganalytics.io';
var responseval = "";

const postData = {
    client_id: APP_ID,
    scope: resource,
    client_secret: APP_SECERET,
    grant_type: 'client_credentials'
  };

  axios.defaults.headers.post['Content-Type'] =
    'application/x-www-form-urlencoded';

    axios
    .post(TOKEN_ENDPOINT, qs.stringify(postData))
    .then(function(response){
        console.log(response);
    })
    .catch(function (err){
        console.log(err.response);
    });

推荐阅读