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

时间:2019-09-17 02:15:42

标签: outlook outlook-addin office-js office-addins

我正在编写Outlook加载项,但权限有问题。当manifest.xml拥有ReadWriteItem权限时,我可以使用令牌通过c#后端服务检索消息。当我将条目更改为ReadWriteMailbox时,我得到一个未经授权的响应,并且相关的错误消息访问被拒绝。检查凭据,然后重试。

我需要其他权限才能在发送电子邮件后尝试查找电子邮件。我阅读的文档表明ReadWriteMailbox是最高的权限级别,并且包含ReadWriteItem提供的权限。这里有我想念的东西吗?

客户端打字稿以获取令牌:

Office.context.mailbox.getCallbackTokenAsync({isRest: true}, async (result:Office.AsyncResult<string>) => {
    if (result.status === Office.AsyncResultStatus.Succeeded) {
        const request = {
            bearerToken : result.value,
            restUrl : Office.context.mailbox.restUrl,
            itemId : Office.context.mailbox.convertToRestId(itemId, Office.MailboxEnums.RestVersion.v2_0)
        }
        await axios.post(MAIL_SERVICE_POLL_URL, request);
     }
});

C#后端:

var outlookClient = _httpClientFactory.CreateClient();
outlookClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", item.BearerToken);
using (var response = await outlookClient.GetAsync($"{item.RestUrl}/v2.0/me/messages/{item.ItemId}?$select=isDraft" ))
{
    if (response.IsSuccessStatusCode &&
        JsonConvert.DeserializeObject<IsDraftModel>(await response.Content.ReadAsStringAsync()).IsDraft)
    {
        // response.StatusCode is Forbidden when ReadWriteMailbox
    }
}

1 个答案:

答案 0 :(得分:0)

万一其他人遇到这个问题,this SO answer帮我解决了。基本上,当更改为<Permissions>ReadWriteMailbox</Permissions>时,查询Outlook Rest API时需要更特定的URL。查询具有 ReadWriteMailbox 权限的草稿电子邮件,其网址应为/v2.0/me/mailFolders/Drafts/messages/,而不是/v2.0/me/messages/(与 ReadWriteItem 权限一起使用):

using (var response = await outlookClient.GetAsync($"{item.RestUrl}/v2.0/me/mailFolders/Drafts/messages/{item.ItemId}?$select=isDraft" ))
{
    if (response.IsSuccessStatusCode &&
        JsonConvert.DeserializeObject<IsDraftModel>(await response.Content.ReadAsStringAsync()).IsDraft)
    {
        // response.StatusCode is now Ok when ReadWriteMailbox
    }
}

类似地,在 SentItems 文件夹中进行过滤时,过滤器的网址为:

var filterUrl = $"{item.RestUrl}/v2.0/me/mailFolders/SentItems/messages?{filter}";