在javascript Azure函数中调用图形API

问题描述 投票:0回答:1

我对Azure Functions相当陌生。我试图在一个HTTP触发的Azure Function中用javascript来消费Graph APIs.我找到了一些与这个参数相关的文档。在Stack Overflow上也有几个问题,但所有的材料都很老了,而且Graph和Azure Functions从那时起都有了改进.当我刚刚创建函数时,它完美地工作。如果我简单地给Auth Token添加一个绑定(https:/graph.microsoft.com),甚至没有接触index.js,函数就停止工作并返回404错误(未找到文件)。连接尝试甚至没有记录在监视器或 Applications Insights 中。我直接从Azure门户构建函数(没有本地部署)。我已经在AAD上创建了一个应用程序,并更改了我的函数应用程序上的身份验证以连接到这个应用程序。还在Microsoft Graph上授权了Azure用户(通过Graph Explorer),但仍然得到这个404错误。我应该检查什么?

根据Tony Ju的回答进行编辑。

我关闭了App服务认证,并按照步骤进行了操作 此处,正如建议的那样。我只是改变了一些东西,使其在Azure Function中工作(帖子是纯Node.js)。实际上,这是我的index.js。

const APP_ID = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX';
const APP_SECERET = 'XXXX~-XXX~XXXXXXXXXXXXX~XXXXXXXXX~';
const TOKEN_ENDPOINT ='https://login.microsoftonline.com/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/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'
};


module.exports = function (context, req) {
    axios.defaults.headers.post['Content-Type'] =
  'application/x-www-form-urlencoded';

    let token = '';

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

XXXX分别取自AAD应用。应用程序(客户端)ID,App客户端秘密和目录(租户)ID。

我的function.json如下。

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    },
    {
      "name": "graphToken",
      "direction": "in",
      "type": "token",
      "resource": "https://graph.microsoft.com",
      "identity": "userFromRequest"
    }
  ]
}

仍然得到404错误。似乎不是代码的问题,而是函数绑定的问题。

在Tony Ju的新评论和进一步的实验之后进行了编辑。

感谢Tony:auth绑定是没有必要的。

还需要进入Function App Service,然后进入Console(在开发工具下),并发布

npm install axios
npm install qs

另外,在我之前列举的index.js中,函数需要为async。

module.exports = async function (context, req) {

这样就可以了 谢谢Tony。

javascript azure-functions microsoft-graph
1个回答
0
投票

我已经在AAD上创建了一个应用程序,并改变了我的函数应用程序上的验证,以连接到这个应用程序。

根据你的描述,你已经启用了对你的函数的认证。在这种情况下,你可以参考以下答案 此处.

如果你不想在你的函数中添加身份验证,你只想在你的函数中调用Microsoft API。你可以使用 客户端凭证流程. 请参考我的回答 此处.

© www.soinside.com 2019 - 2024. All rights reserved.