首页 > 解决方案 > Microsoft Graph API 获取事件开始返回 401 UnAuthorized

问题描述

我有一个使用 Microsoft Outlook rest api 来获取日历事件的应用程序。

按照以下说明进行操作: https ://docs.microsoft.com/en-us/previous-versions/office/office-365-api/api/version-2.0/use-outlook-rest-api

该应用程序运行良好,但几天前我突然收到获取事件 API 的未经授权的错误 (401)

查看响应标头,这是异常“2000003;reason="观众声明值无效' https://graph.microsoft.com '。";error_category="invalid_resource"

下面是我的代码

HttpClient client = new HttpClient();
            var values = new Dictionary<string, string>
{
   { "client_id", "clientId" },
   { "scope", "https://graph.microsoft.com/Calendars.ReadWrite People.Read offline_access" },
   { "code", code },
   { "state", "12345" },
   { "redirect_uri", "http://localhost:3000/home" },
   { "grant_type", "authorization_code" },
   { "client_secret", "secret key" }
};

            var content = new FormUrlEncodedContent(values);

            var response = await client.PostAsync("https://login.microsoftonline.com/common/oauth2/v2.0/token", content);
            string token = string.Empty;
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var responseString = await response.Content.ReadAsStringAsync();
                var tokenResponse = JsonConvert.DeserializeObject<TokenResponse>(responseString);
                token = tokenResponse.access_token;
            }
            client.DefaultRequestHeaders.Add("Accept", "application/json");
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            Events events = new Events();
            var responseEvents = await client.GetAsync("https://outlook.office.com/api/v2.0/me/events");
            if (responseEvents.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var responseString = await responseEvents.Content.ReadAsStringAsync();
                events = JsonConvert.DeserializeObject<Events>(responseString);
                ViewBag.Message = token;
            }
            else
            {
                var responseString = await responseEvents.Content.ReadAsStringAsync();
            }

标签: microsoft-graph-apioutlook-restapi

解决方案


能够通过将范围从 https://graph.microsoft.com/Calendars.ReadWrite更改为https://outlook.office.com/Calendars.ReadWrite来解决此问题。

随着我上面代码的这种变化,它现在开始正常工作了。

首先不确定为什么它更早地使用范围https://graph.microsoft.com/Calendars.ReadWrite


推荐阅读