首页 > 解决方案 > 无法从 Microsoft Graph API 获取邮件

问题描述

我正在尝试使用 Graph API 从我的 Outlook 帐户中获取邮件。我正在使用我的组织 Outlook 帐户,我从中配置了我的应用程序。

我成功地能够从 api 获取 auth2 令牌,https://login.microsoftonline.com/common/oauth2/v2.0/token但是在查询 api 时,我收到以下错误

{
    "error": {
        "code": "BadRequest",
        "message": "Current authenticated context is not valid for this request. This occurs when a request is made to an endpoint that requires user sign-in. For example, /me requires a signed-in user.  Acquire a token on behalf of a user to make requests to these endpoints.  Use the OAuth 2.0 authorization code flow for mobile and native apps and the OAuth 2.0 implicit flow for single-page web apps.",
        "innerError": {
            "request-id": "807ce785-38b6-4fbb-b670-6419768b08c3",
            "date": "2019-06-21T11:59:26"
        }
    }
}

我使用的 APIhttps://graph.microsoft.com/v1.0/me/messages和我使用的标头是:

X-AnchorMailbox:{{my_email}}
Accept:application/json
Authorization:Bearer {{token}}

我正在使用的应用程序是用于查询 api 的邮递员。

标签: azureazure-ad-graph-api

解决方案


如错误消息所述,您获得的令牌似乎没有登录用户上下文。您可能使用 OAuth2 客户端凭据流来获取令牌,而对于调用 /me 方法,您需要使用隐式授权流,这会将用户重定向到 login.microsoftonline.com 进行登录,然后使用获得的(通过委托权限)令牌调用图表。

所以你基本上有两个选择:

  1. 使用委派权限、隐式授权流程(用户以交互方式登录)和https://graph.microsoft.com/v1.0/me/messages
  2. 使用应用程序权限、客户端凭据授予流程(无需用户登录)和https://graph.microsoft.com/v1.0/users/ {userPrincipalName}/messages

推荐阅读