【问题标题】:microsoft-graph-client throws '#<GraphError>' error on API callmicrosoft-graph-client 在 API 调用时抛出“#<GraphError>”错误
【发布时间】:2020-11-02 16:14:26
【问题描述】:

我想从我的 Node 后端使用 Graph API。首先,我通过调用acquireTokenWithClientCredentials 方法从adal-node 获取访问令牌。所以我的令牌响应是

我安装了 @microsoft/microsoft-graph-client 软件包并尝试按照此处的指南进行操作 https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/samples/node/main.js 。对于isomorphic-fetch 导入,我安装了isomorphic-fetch 包。

async function bootstrap() {
  // ...
  const session: TokenResponse = await authenticationService.getSession(); // call the 'acquireTokenWithClientCredentials' function

  const client: Client = Client.init({
    authProvider: (done) => {
      done(null, session.accessToken);
    },
  });

  try {
    await client.api('/me').get();
  } catch (error) {
    throw error;
  }
}

API 调用引发异常。但我不知道出了什么问题,因为错误只记录了

(node:20561) UnhandledPromiseRejectionWarning: #<GraphError>

出了什么问题或遗漏了什么?如果您需要更多信息,请告诉我。但我希望我的描述应该足以复制:)提前谢谢。


更新

应用程序未以用户身份登录,应作为后台服务运行。所以也许我无法访问/me,因为应用程序不是用户。但是当我将/me 更新为/users(这个端点应该可以工作)时,我仍然得到同样的错误。

所以我当前访问/users时的访问令牌是

【问题讨论】:

    标签: azure-active-directory microsoft-graph-api adal adal.js microsoft-graph-sdks


    【解决方案1】:

    您不能使用Client credential flow 获取/me 端点的访问令牌。您应该改用auth code flow(acquireTokenWithAuthorizationCode)。然后您可以为已登录的用户拨打/me

    如果您必须使用客户端凭据流,您应该为特定用户调用/users/{id | userPrincipalName}

    另外,如果你要调用Microsoft Graph API,你用来获取访问令牌的资源的值应该是https://graph.microsoft.com

    var resource = 'https://graph.microsoft.com';
    

    【讨论】:

    • 嘿,谢谢你的回复。你介意解释一下为什么我应该使用acquireTokenWithAuthorizationCode 吗?授权码从哪里来?它期待重定向 uri,但我使用 Node 后端 ...
    • 编辑:我的应用程序在没有用户的情况下作为服务运行,所以我认为我的代码是正确的,但我无法访问me,因为该服务不是用户。但是当我将 /me 更改为 /users 时,我仍然会收到该错误
    • @Question3r 我明白了。然后,您应该使用客户端凭据流。资源的价值是什么?
    • @Question3r 您是否将用户 id/userPrincipalName 与用户一起添加?(/users/{id | userPrincipalName})
    • @Tony Ju 我更新了我的问题,最后一张图片显示我现在正在使用https://graph.microsoft.com 作为资源。不,我没有添加用户 ID。我想列出所有用户,因为我只使用模拟账户,只有我自己
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多