使用JavaScript从Azure函数对Graph API进行身份验证

时间:2020-09-08 01:04:44

标签: azure azure-functions microsoft-graph-api msal.js

我想使用NodeJS创建一个Azure函数并向Graph API进行身份验证。通过阅读,我知道我必须使用客户端凭据流。我正在使用此代码,发布者:

const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> 
    const APP_ID = [appId]';
    const APP_SECERET = '[secret]';
    const TOKEN_ENDPOINT ='https://login.microsoftonline.com/[tenantid]/oauth2/v2.0/token';
    const MS_GRAPH_SCOPE = 'https://graph.microsoft.com/.default';
    
    const axios = require('axios');
    const qs = require('qs');

    const postData = {
        client_id: APP_ID,
        scope: MS_GRAPH_SCOPE,
        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(response => {
        context.res = {
           
            body: response.data //JSON.stringify(w, null, 4)
        };
      })
      .catch(error => {
        console.log(error);
      });

};

如这篇文章所述:How to get users from azure active directory to azure function

但是,这没有用,因为它甚至没有向Azure发出请求。缺少什么吗?在使用Node时,我不能使用MSAL.JS进行服务器到服务器的调用吗?还是仅用于基于Web的应用程序,并且不能与Azure函数一起使用?

我看到的大多数示例都与.Net相关,并且它们使用的是一堆nuget包等。JavaScriptazure函数不支持我需要的吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

我不知道您为什么说它甚至没有发出天蓝色的请求,我用与您几乎相同的代码对其进行了测试,并且效果很好。我提供以下详细步骤,供您参考。

1。。我在VS代码中创建了一个类型脚本函数(不要忘记在代码的第二行中声明require),我的函数代码显示为:

import { AzureFunction, Context, HttpRequest } from "@azure/functions"
declare var require: any

const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {

    const APP_ID = 'xxxxxx';
    const APP_SECERET = 'xxxxxx';
    const TOKEN_ENDPOINT ='https://login.microsoftonline.com/xxxxxx/oauth2/v2.0/token';
    const MS_GRAPH_SCOPE = 'https://graph.microsoft.com/.default';

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

    const postData = {
        client_id: APP_ID,
        scope: MS_GRAPH_SCOPE,
        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(response => {
        console.log('=====below is response====');
        console.log(response.data);
        console.log('=====above is response====');
        context.res = {
           
            body: response.data
        };
      })
      .catch(error => {
        console.log(error);
      });

};

export default httpTrigger;

2。。我通过以下命令安装axiosqs模块:

npm install axios
npm install qs

3。。要启动该功能,我运行了命令:

npm install
npm start

4。。请求该函数后,得到的结果为: enter image description here