我正在尝试使用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"))
{
}
答案 0 :(得分:0)
您Authority
不太正确:
resource=https://graph.microsoft.com
是旧设置,不用于v2端点(也就是使用Scope而不是Resources进行身份验证)。
ConfidentialClientApplicationBuilderhandes
会自动设置OAuth授权,因此无需指定grant_type=client_credentials
。
权限仅应包含身份验证权限(https://login.microsoftonline.com/
)和租户ID。解决此问题的最简单方法是使用AzureCloudInstance.AzurePublic
枚举
您的令牌代码应如下所示:
app = ConfidentialClientApplicationBuilder
.Create(ClientId)
.WithClientSecret(ClientSecret)
.WithAuthority(AzureCloudInstance.AzurePublic, TenantId)
.Build();
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
AuthenticationResult result = null;
try
{
result = await app
.AcquireTokenForClient(scopes)
.ExecuteAsync();
}
catch (MsalServiceException ex)
{
}
注意:您将无法通过@outlook.com
帐户使用此方法。个人帐户不支持client_credentials
。
答案 1 :(得分:-1)