c# - 使用 Graph API 从 Azure AD 检索所有用户时出现 403 禁止

标签 c# azure-active-directory microsoft-graph-api

当我尝试让所有用户使用 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 中注册的客户端拥有所有权限:

enter image description here

我错过了什么吗?

最佳答案

您已授予委派权限,但使用客户端凭据调用 API。

授予您的应用程序对 API 的应用权限,您就可以调用它。 仅当您代表用户调用电话时,委派权限才适用。

关于c# - 使用 Graph API 从 Azure AD 检索所有用户时出现 403 禁止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55167021/

相关文章:

c# - 为什么 Form 得不到焦点?

c# - 如何在一个 SQL 语句中比较来自不同数据库的两个值

microsoft-graph-api - 无法更新事件 Beta 端点

javascript - 使用 Microsoft Graph 客户端创建日历事件

node.js - 无法使用 Azure 应用程序通过图形 API 访问一个驱动器

c# - 多线程 EF6 中的主键冲突

c# - Parallel.ForEach 未按 C# 中 ConcurrentBag 中的预期添加项目

azure - 有没有办法返回 Microsoft Graph API 中给定对象 ID 的用户的身份验证手机号码?

azure - 如何知道用户是否选择在 Azure B2C 中保持登录状态

c# - 操作返回无效状态代码 'Unauthorized' '