用于访问 Microsoft Graph 的 Azure ADAL 库 API

Azure ADAL library to access Microsoft graph API

我已经在 Azure AD 中注册了一个本机应用程序,并授予所有委托访问图的权限 API.I 我正在尝试使用控制台解决方案 (exe) 测试此解决方案,并使用以下代码使用客户端 ID 和密码

  private static async void AcquireTokenAsync() {
            AuthenticationContext context = new AuthenticationContext("https://login.windows.net/xxxxxx-xxxx-485b-a40f-xxxxxxxx/oauth2/token", true);
            var result = await context.AcquireTokenAsync("https://graph.microsoft.com",
                                                      new ClientCredential("xxxxxx-32cf-xxxx-8888-555555555555",
                                                      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxV89cWfH0w="
                                                      )
                                                      );

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + result.AccessToken);
            HttpResponseMessage response = await client.GetAsync("https://graph.microsoft.com/v1.0/users/");
            string retResp = await response.Content.ReadAsStringAsync();
            string token = result.AccessToken;
            Console.WriteLine(token + "\n" + restResp);

}

检索没有问题 token.I 正在获取访问令牌,但在图形中出现以下错误/响应 api 使用令牌调用

{
  "error": {
    "code": "Authorization_RequestDenied",
    "message": "Insufficient privileges to complete the operation.",
    "innerError": {
      "request-id": "cb7aaaa9-d9a0-485a-7777-b5bfe68ba771",
      "date": "2017-07-22T11:01:49"
    }
  }
}

请指出问题所在

请查看委托权限和仅应用权限之间的区别 here

您 运行 遇到的问题是您已请求对图形的委派权限 API,但随后您正在获取一个应用专用令牌,这需要不同类型的权限。如果您 take a look at your token 您会发现您的令牌缺少调用图表所需的声明。

相反,您需要执行以下操作之一:

  1. 按照授权代码授予流程获取应用程序 + 用户令牌。这将导致对 Graph 的委托访问,并且您的调用应该有效。
  2. 请求仅应用程序对图表的权限API。这将允许您当前的身份验证方法获得对 Graph API 的访问权限。但是,所有仅限应用程序的权限都需要管理员同意该应用程序。