c# - 使用 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 吗?
解决方案
您使用了错误的资源,您需要获取 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());
}
}
}
推荐阅读
- html - Angular - View 打印旧值和新值
- python - 对于字典,将键和值都与列表中的值进行比较
- css - 如何更改子菜单项颜色
- reactjs - 反应路由器访问控制
- python - 将正则表达式规则应用于宽数据框
- applescript - 是否可以使用布尔测试说明符过滤列表?
- reactjs - 有没有办法在反应网页中显示 orientdb 交互式图形?
- symfony4 - Symfony 4 - EasyAdmin Bundle - 默认表单值
- objective-c - 如何禁用 react native webview 的默认上下文菜单,并调用 react prop 而不是原生的?
- json - 如何 sort_by 使用 jq 获取最新对象