当我尝试让所有用户使用 Graph API 时,我收到来自 Azure AD 的 403 Forbidden 响应:
public static async Task<string> AppAuthenticationAsync()
{
var tenant = ConfigurationManager.AppSettings["ida:TenantId"];
var resource = "https://graph.microsoft.com/";
var clientID = ConfigurationManager.AppSettings["ida:ClientId"];
var secret = ConfigurationManager.AppSettings["ida:AppKey"];
var authority = $"https://login.microsoftonline.com/{tenant}";
var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority);
var credentials = new ClientCredential(clientID, secret);
var authResult = await authContext.AcquireTokenAsync(resource, credentials);
return authResult.AccessToken;
}
public static async Task<string[]> GetUsersListAsync(HttpClient client)
{
var payload = await client.GetStringAsync($"https://graph.microsoft.com/v1.0/users");
var obj = JsonConvert.DeserializeObject<JObject>(payload);
var users = from g in obj["value"]
select g["displayName"].Value<string>();
return users.ToArray();
}
下面是代码,它在我的 Controller 中使用来获取结果
var token = await AppAuthenticationAsync();
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var users = await GetUsersListAsync(client);
lstADUsers = users.ToList();
}
在 Azure AD 中注册的客户端拥有所有权限:
我错过了什么吗?
最佳答案
您已授予委派权限,但使用客户端凭据调用 API。
授予您的应用程序对 API 的应用权限,您就可以调用它。 仅当您代表用户调用电话时,委派权限才适用。
关于c# - 使用 Graph API 从 Azure AD 检索所有用户时出现 403 禁止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55167021/