代码之家  ›  专栏  ›  技术社区  ›  Rolwin Crasta

Microsoft Graph API获取事件开始返回401未授权

  •  2
  • Rolwin Crasta  · 技术社区  · 6 年前

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

    https://docs.microsoft.com/en-us/previous-versions/office/office-365-api/api/version-2.0/use-outlook-rest-api

    应用程序运行良好,但几天前突然出现Get Events API的未授权错误(401)

    “2000003;reason=”访问群体声明值无效' https://graph.microsoft.com

    下面是我的代码

    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();
                }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Rolwin Crasta    6 年前

    通过改变作用域 https://graph.microsoft.com/Calendars.ReadWrite https://outlook.office.com/Calendars.ReadWrite

    在我上面的代码中有了这个改变,它现在开始正常工作了。

    首先不确定为什么它能在scope上运行得更早

    推荐文章