【发布时间】:2019-06-11 14:32:46
【问题描述】:
我正在使用 Microsoft Graph,并创建了一个可以读取特定用户邮件的应用。
但是,在获得访问令牌并尝试读取邮件文件夹后,我收到了 401 Unauthorized 答案。详细信息是:
令牌不包含权限,或权限无法理解。
这似乎是一个非常明确的信息,但不幸的是我无法找到解决方案。 这是我到目前为止所做的:
- 在https://apps.dev.microsoft.com注册应用程序
给予 应用程序权限 Mail.Read、Mail.ReadWrite (https://docs.microsoft.com/en-us/graph/api/user-list-mailfolders?view=graph-rest-1.0)
// client_secret retrieved from secure storage (e.g. Key Vault) string tenant_id = "xxxx.onmicrosoft.com"; ConfidentialClientApplication client = new ConfidentialClientApplication( "..", $"https://login.microsoftonline.com/{tenant_id}/", "https://dummy.example.com", // Not used, can be any valid URI new ClientCredential(".."), null, // Not used for pure client credentials new TokenCache());
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
AuthenticationResult result = client.AcquireTokenForClientAsync(scopes).Result;
string token = result.AccessToken;
到目前为止一切顺利。我确实得到了一个令牌。
现在我想阅读邮件文件夹:
url = "https://graph.microsoft.com/v1.0/users/{username}/mailFolders"; handler = (HttpWebRequest)WebRequest.Create(url); handler.Method = "GET"; handler.ContentType = "application/json"; handler.Headers.Add("Authorization", "Bearer " + token); response = (HttpWebResponse)handler.GetResponse(); using (StreamReader sr = new StreamReader(response.GetResponseStream())) { returnValue = sr.ReadToEnd(); }
这次我收到一条 401 消息,其中包含详细信息:
令牌不包含权限,或权限无法理解。
我搜索了互联网,但找不到我的令牌为何没有权限的答案。
感谢您的宝贵时间!
更新 1
如果我使用 Graph Explorer 来读取邮件文件夹,那么它可以正常工作。此外:如果我从浏览器中获取令牌 ID,然后在我的第二段代码中使用它,那么我也会得到一个结果。所以,问题实际上是我从第一步收到的令牌。
【问题讨论】:
-
您可以将您的令牌粘贴到jwt.io。在那里,您可以检查有效负载是否真的列出了所需的权限。否则,请重新检查您授予的权限,并可能为您的应用程序重新运行管理员同意。
-
嗨奥利弗,感谢您的回复。我已将副本粘贴到验证器中。解码后的响应似乎没问题,但老实说我不知道在哪里寻找权限。
-
如果你看一下解码后的有效载荷,有一些众所周知的 jwt 属性,如
iat、nbf、exp。再低一点,有一个属性scp。这包含您可以访问的所有范围。这是一个空格分隔的列表,应该包含文本 Mail.Read 或 Mail.ReadWrite。如果不是这样,你没有权限。 -
这可能是问题所在:我根本没有 scp 属性。
-
那么您请求 graph.microsoft.com 令牌的方式有问题。不知道是什么,但我请求the application token differently then you。
标签: c# oauth-2.0 office365 microsoft-graph-api