Microsoft Graph API守护程序-错误:ResourceNotFound消息:无法发现资源

时间:2020-01-14 17:26:21

标签: c# asp.net-web-api microsoft-graph-api microsoft-graph-mail microsoft-graph-calendar

我正在尝试使用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"))
{

}

2 个答案:

答案 0 :(得分:0)

Authority不太正确:

  1. resource=https://graph.microsoft.com是旧设置,不用于v2端点(也就是使用Scope而不是Resources进行身份验证)。

  2. ConfidentialClientApplicationBuilderhandes会自动设置OAuth授权,因此无需指定grant_type=client_credentials

  3. 权限仅应包含身份验证权限(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)

enter image description here文档指出,您必须同时添加CalenderRead和CalenderReadWrite。如果没有,如果您使用个人帐户,我将使用委派权限。我还要去ms.jwt,他们在这里检查您的令牌并告诉您您拥有什么权限,您需要什么才能调用日历端点