NodeJs AxiosError:请求失败,状态代码 403(Mircosft Graph API)

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

我使用 MS Graph API 通过 Lambda 和 NodeJs 读取用户日历事件。这是我正在做的事情的流程: 首先,我在 AAD 中注册了一个应用程序并授予了委托权限,例如

  • 日历.读写
  • 用户.阅读

代码流程如下: 首先我得到访问令牌

var options = {
      method: 'POST',
      url: `https://login.microsoftonline.com/af2601c4-9adasd-******-99fd-e15104d7d9fc/oauth2/v2.0/token`,
      data: data(I am passing the clientid, client_secret, scope etc)
    };

之后,我尝试阅读日历事件

try{ const response = await axios.get('https://graph.microsoft.com/v1.0/users/108ca636-***-41e2-8dd5-********/events', {
        headers: {
            Authorization: `Bearer ${accessToken}`
        }
    });

但是它给了我这个错误

"message": "Request failed with status code 403",
    "name": "AxiosError",
    "stack": "AxiosError: Request failed with status code 403

PS:我解码了访问令牌,但没有看到我在 AAD 中向应用程序授予的任何权限{在上图中}。 预先感谢。

node.js amazon-web-services aws-lambda azure-active-directory microsoft-graph-api
1个回答
0
投票

当您使用委托类型的权限时,会发生错误,该权限不适用于客户端凭据流程。

最初,当我授予 Delegated

 权限并使用该令牌通过 Postman 获取用户事件时,我也遇到了 
同样的错误

GET https://graph.microsoft.com/v1.0/users/user_id/events

回复:

enter image description here

要解决该错误,您需要授予 Application 类型的权限,并确保授予管理员同意,如下所示:

enter image description here

现在,我通过 Postman 使用 客户端凭据 流再次生成令牌,参数如下:

POST https://login.microsoftonline.com/tenantId/oauth2/v2.0/token
grant_type:client_credentials
client_id: appId
client_secret: secret 
scope: https://graph.microsoft.com/.default

回复:

enter image description here

您可以在 jwt.ms 网站中解码此令牌并检查

roles
声明权限:

enter image description here

当我使用此令牌通过以下图形 API 调用来获取用户事件时,我成功获得了响应,如下所示:

GET https://graph.microsoft.com/v1.0/users/user_id/events

回复:

enter image description here

如果您想使用委托权限,请使用授权代码流等交互式流程。

参考: Microsoft 身份平台和 OAuth 2.0 授权代码流程

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