简体   繁体   English

Office365 REST API使用C#ADAL返回Unauthorized

[英]Office365 REST API returns Unauthorized with C# ADAL

I'm building a WPF-App. 我正在构建一个WPF-App。 First get Events and later on create Events via O365 RestAPI. 首先获取事件,然后通过O365 RestAPI创建事件。

I'm able to get events with: 我能够通过以下方式获得活动:

result = await authContext.AcquireTokenAsync(graphResourceId, clientId, redirectUri, new PlatformParameters(PromptBehavior.Auto));Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
                    string today = DateTime.Today.ToString("yyyy-MM-dd", CultureInfo.CurrentCulture);
                    string graphRequest = String.Format(CultureInfo.CurrentCulture, "https://outlook.office365.com/api/v2.0/me/calendarview?startDateTime=" + today + "T00:00:00&endDateTime=" + today + "T23:59:00&$select=Subject,organizer,start,end,attendees&$orderby=start/datetime%20asc");
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, graphRequest);
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                    request.Headers.Add("Prefer", "outlook.timezone=\"W. Europe Standard Time\"");
                    HttpResponseMessage response = HttpClient.SendAsync(request).Result;

                    if (!response.IsSuccessStatusCode)
                        throw new WebException(response.StatusCode.ToString() + ": " + response.ReasonPhrase);

But when I try to create Events, I will receive a "Unauthorized" using the same Token. 但是当我尝试创建事件时,我将使用相同的令牌收到“未授权”。 My App have permissions to read and write calenders. 我的应用程序有权读取和写入日历。

This is my code: 这是我的代码:

string postBody = "{'Subject':" + "'Discuss the Calendar REST API'," +
                            "'Body':{ " +
                                          "'ContentType':'HTML'," +
                              "'Content': 'I think it will meet our requirements!'},"
                           + "'Start': { DateTime: '" + 
                              start + "',"
                                    + " 'TimeZone': 'W. Europe Standard Time'}," +
                               "'End':{'DateTime': '" + end + "'," +
                                    "'TimeZone': 'W. Europe Standard Time'},"
                                + "'Attendees':[{" +
                                "'EmailAddress':{"
                                 + "'Address': '" + MailTB.Text + "'"
                                + 
                                " },"
                                + "'Type': 'Required'}]}";


    var emailBody = new StringContent(postBody, System.Text.Encoding.UTF8, "application/json");
        AuthenticationContext authContext = new AuthenticationContext(authority, new FileCache());
        AuthenticationResult result = await authContext.AcquireTokenAsync(graphResourceId, clientId, redirectUri, new PlatformParameters(PromptBehavior.Auto));

        Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
    string today = DateTime.Today.ToString("yyyy-MM-dd", CultureInfo.CurrentCulture);
    string graphRequest = String.Format(CultureInfo.CurrentCulture, "https://outlook.office365.com/api/v2.0/me/events");
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, graphRequest);
    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
    request.Headers.Add("Prefer", "outlook.timezone=\"W. Europe Standard Time\"");
        HttpResponseMessage response = MainWindow.HttpClient.PostAsync(graphRequest, emailBody).Result;

        if (!response.IsSuccessStatusCode)
            throw new WebException(response.StatusCode.ToString() + ": " + response.ReasonPhrase);

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, graphRequest); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,graphRequest); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); request.Headers.Authorization = new AuthenticationHeaderValue(“Bearer”,result.AccessToken); request.Headers.Add("Prefer", "outlook.timezone=\\"W. Europe Standard Time\\""); request.Headers.Add(“Prefer”,“outlook.timezone = \\”W。Europe Standard Time \\“”); HttpResponseMessage response = MainWindow.HttpClient.PostAsync(graphRequest, emailBody).Result; HttpResponseMessage响应= MainWindow.HttpClient.PostAsync(graphRequest,emailBody).Result;

The code you you send the post request will not send the headers you set since all the headers are set for the request parameter but you were not using it in the post. 您发送帖子请求的代码将不会发送您设置的标题,因为所有标题都是为request参数设置的,但您没有在帖子中使用它。

To send the post with access_token, you can refer code below: 要使用access_token发送帖子,您可以参考以下代码:

var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization= new AuthenticationHeaderValue("Bearer", accessToken);
httpClient.DefaultRequestHeaders.Add("Prefer", "outlook.timezone=\"W. Europe Standard Time\"");
HttpResponseMessage response = httpClient.PostAsync(graphRequest, emailBody).Result;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM