【发布时间】:2020-05-01 11:31:51
【问题描述】:
我正在尝试使用 Microsoft Graph API v1.0 创建一个守护程序。
我已在获得管理员同意的情况下使用应用程序权限 Calendars.ReadWrite 和 User.Read.All 注册了我的应用程序。
我正确获取了访问令牌,并调用了 GetUserId,它返回用于设置 requestURI 的用户 ID。
之后我想检索 Outlook 日历:
var id = await GetUserId(result.AccessToken);
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
String requestURI = $"https://graph.microsoft.com/v1.0/users/{id}/calendars";
var response = await httpClient.GetAsync(requestURI);
var responseString = await response.Content.ReadAsStringAsync();
但我收到此错误:
{
"error": {
"code": "ResourceNotFound",
"message": "Resource could not be discovered.",
"innerError": {
"request-id": "5ecd547b-9281-4824-94e5-095691e759aa",
"date": "2020-01-14T16:44:16"
}
}
}
当我将requestURI 设置为users/{id} 或organization 时,请求工作正常,但添加/calendars、/events 或/mailFolder 会导致上述错误。
我认为我的问题是我使用了个人帐户。我需要使用工作或学校帐户吗?是否可以使用个人帐户?我的错误还有其他原因吗?
更新:检索令牌的代码:
app = ConfidentialClientApplicationBuilder
.Create(ClientId)
.WithClientSecret(ClientSecret)
.WithAuthority($"https://login.microsoftonline.com/{TenantId}/oauth2/v2.0/token&grant_type=client_credentials&resource=https://graph.microsoft.com")
.Build();
string[] scopesClient =
new string[] { $"https://graph.microsoft.com/.default" };
AuthenticationResult result = null;
try
{
result = await app.AcquireTokenForClient(scopesClient).ExecuteAsync();
}
catch (MsalServiceException ex) when(ex.Message.Contains("AADSTS70011"))
{
}
【问题讨论】:
-
你是如何获得代币的,你所说的“个人账户”是什么意思?根据日志,此令牌是由 AAD 租户使用
User.Read.All和Calendar.ReadWrite应用程序范围发出的。如果您使用的是 Outlook.com 帐户,则该令牌将仅支持委托范围。 -
感谢@Mark 回复。这是获取token的代码
app =ConfidentialClientApplicationBuilder.Create(ClientId).WithClientSecret(ClientSecret).WithAuthority($"https://login.microsoftonline.com/{TenantId}/oauth2/v2.0/token&grant_type=client_credentials&resource=https://graph.microsoft.com").Build(); string[] scopesClient=new string[] { $"https://graph.microsoft.com/.default" }; AuthenticationResult result = null; try { result = await app.AcquireTokenForClient(scopesClient).ExecuteAsync(); }catch (MsalServiceException ex) when(ex.Message.Contains("AADSTS70011")){} -
我使用 Outlook.com 帐户和非 Outlook.com 帐户都收到上述错误。
标签: c# asp.net-web-api microsoft-graph-api microsoft-graph-mail microsoft-graph-calendar