我很难向Outlook API发送POST请求。

我正在本地计算机上工作,并将redirectUrl定义为我的localhost:port

我的GET请求有效:

var apiUrl = "https://outlook.office.com/api/v2.0/me/calendarview?startdatetime=" + startDateTime + "&enddatetime=" + endDateTime + "&$top=" + 10;

$.ajax({
    type: 'GET',
    url: apiUrl,
    headers: {
        "Authorization": "Bearer " + token
    }
}).done(function (data) {
    processResults(data);
}).fail(function (response) {
    handleFailure();
});


但是当我尝试发送POST时,我收到了以下消息:


  访问被拒绝。检查凭据,然后重试。


我的代码是:

var apiUrl = "https://outlook.office.com/api/v2.0/me/events";
var postData = {
  "Subject": "Plan summer company picnic",
  "Body": {
    "ContentType": "HTML",
    "Content": "Let's kick-start this event planning!"
  },
  "Start": {
      "DateTime": "2019-01-15T11:00:00",
      "TimeZone": "Pacific Standard Time"
  },
  "End": {
      "DateTime": "2019-01-15T12:00:00",
      "TimeZone": "Pacific Standard Time"
  },
  "Attendees": [
    {
      "EmailAddress": {
        "Address": "[email protected]",
        "Name": "Name Here"
      },
      "Type": "Required"
    }
  ]
};

$.ajax({
    type: 'POST',
    url: apiUrl,
    headers: {
        "Authorization": "Bearer " + token
    },
    contentType: 'application/json',
    data: JSON.stringify(postData)
}).done(function (data) {
    processResults(data);
}).fail(function (response) {
    handleFailure();
});


在这两种情况下,我都使用相同的令牌,因此这可能不是登录问题。我还允许在应用程序中使用Calendars.ReadWrite

更新

我清除了缓存,登录,进行了GET调用,然后进行了POST调用,然后再次进行了GET调用。这两个GET调用均有效,因此问题不是令牌或缓存问题。

最佳答案

问题出在身份验证过程中,显然在每个请求上我都必须指定scope,并且它应包含多个权限。

在标题中,我发现了这一点:


  x-ms-diagnostics:2000008; reason =“访问此API需要以下权限:'Calendars.Read.All,Calendars.Read.Shared,Calendars.ReadWrite.All,Calendars.ReadWrite.Shared'。但是,该应用程序仅授予以下权限:'Calendars.Read,Calendars.ReadWrite'。“; error_category =” invalid_grant“


即使这是错误的,因为Calendars.Read.AllCalendars.ReadWrite.All不存在,所以它应该是Calendars.ReadCalendars.ReadWrite

身份验证请求应如下所示:

var authUrl = authServer +
          "response_type=" + encodeURI(token) +
          "&client_id=" + encodeURI(clientId) +
          "&scope=" + encodeURI("https://outlook.office.com/Calendars.Read https://outlook.office.com/Calendars.Read.Shared  https://outlook.office.com/Calendars.ReadWrite https://outlook.office.com/Calendars.ReadWrite.Shared") +
          "&redirect_uri=" + redirectUrl +
          "&state=" + stateParam;

09-25 19:27