首页 > 解决方案 > 使用 HttpClient 向 Microsoft Graph 请求用户列表时出现未经授权的问题

问题描述

我正在尝试通过 Microsoft Graph 获取有关用户的信息 https://graph.microsoft.com/v1.0/users

它返回一个401 - Unauthorized

{
  "error": {
    "code": "InvalidAuthenticationToken",
    "message": "Access token validation failure. Invalid audience.",
    "innerError": {
      "request-id": "3157d513-6f31-4d2d-a3d7-a97eed7207ba",
      "date": "2019-12-11T05:39:02"
    }
  }
}

我的代码:

AuthenticationContext authContext =
    new AuthenticationContext(string.Format(CultureInfo.InvariantCulture,
        "https://login.microsoftonline.com/{0}", "my-domain name"));

ClientCredential clientCred =
    new ClientCredential("Client-id", "Client-Secret-id");

AuthenticationResult authenticationResult = authContext
    .AcquireTokenAsync("https://graph.windows.net", clientCred).Result;

var token = authenticationResult.AccessToken;

var client = new HttpClient();
var uri = "https://graph.microsoft.com/v1.0/me/";

client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(token);
var response = await client.GetAsync(uri);

我哪里做错了?为什么我没有获得正确的访问令牌?有人可以帮我使用 MS Graph 吗?

标签: c#azure-active-directorymicrosoft-graph-apiasp.net-core-2.1

解决方案


您使用了错误的资源,您需要获取 Microsoft Graph 而不是 AAD Graph 的令牌,它应该是https://graph.microsoft.com,而不是https://graph.windows.net.

AuthenticationResult authenticationResult = authContext.AcquireTokenAsync("https://graph.microsoft.com",
                      clientCred).Result;

更新

确保您授予User.Read.All应用程序权限。

在此处输入图像描述 在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

然后尝试如下代码,它适用于我。

using System;
using System.Net.Http;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            string _authString = "https://login.microsoftonline.com/xxxxxx.onmicrosoft.com";
            string _clientId = "<client-id>";
            string _clientSecret = "<client-secret>";
            AuthenticationContext authenticationContext = new AuthenticationContext(_authString, false);
            ClientCredential clientCred = new ClientCredential(_clientId, _clientSecret);
            AuthenticationResult authenticationResult;
            authenticationResult = authenticationContext.AcquireTokenAsync("https://graph.microsoft.com", clientCred).GetAwaiter().GetResult();
            Console.WriteLine(authenticationResult.AccessToken);

            var token = authenticationResult.AccessToken;

            var client = new HttpClient();
            var uri = "https://graph.microsoft.com/v1.0/users";

            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            client.DefaultRequestHeaders.Accept.Clear();
            //GET Method  
            HttpResponseMessage response = client.GetAsync(uri).GetAwaiter().GetResult();
            Console.WriteLine(response.Content.ReadAsStringAsync().Result.ToString());
        }
    }
}

在此处输入图像描述


推荐阅读