我正在使用 Microsoft Graph 并已创建一个从特定用户读取邮件的应用程序。然而,在获取访问令牌并尝试读取邮件文件夹后,我收到了 401 未经授权的回答。详细消息如下:令牌不包含权限,或者无法理解权限。这似乎是一个很明确的消息,但不幸的是我无法找到解决方法。到目前为止,我已经完成以下工作:
到目前为止一切顺利,我已经获得了一个令牌。
现在我想读取邮件文件夹:
- 在 https://apps.dev.microsoft.com 上注册应用程序
授予应用程序权限 Mail.Read、Mail.ReadWrite (https://learn.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并在我的第二段代码中使用它,那么也会得到结果。因此,问题确实是我从第一步收到的令牌。
iat
、nbf
和exp
。再往下一点,有一个名为scp
的属性。它包含了您可以访问的所有范围。这是一个以空格分隔的列表,应该包含文本Mail.Read或Mail.ReadWrite。如果不是这种情况,那么您没有权限。 - Oliver