使用 User.ReadBasic.All 从 azure AD 读取用户的权限问题?

Permissions problems reading users from azure AD with User.ReadBasic.All?

我正在尝试获取 azure 用户,但出现权限错误,即使我放置的不是用户而是 ME,为什么?这不应该是我不需要管理员同意的东西吗?感谢您的帮助!!


            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                .Create("****")
                .WithTenantId("****")
                .WithClientSecret("***")
                .Build();

            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
            // Create a new instance of GraphServiceClient with the authentication provider.
            GraphServiceClient graphClient = new GraphServiceClient(authProvider);

            var user = await graphClient.Users
                .Request()
                .WithScopes(graphScopes)
                .Select(u => new {
                    u.DisplayName
                })
                .GetAsync();
    ```

对于这个问题,您似乎没有权限获取用户。可以参考图api的document,需要权限如下:

所以请到你的azure ad中注册的应用程序,点击“API权限”,然后添加权限。

添加权限后,请不要忘记点击“grand admin consent for xxx”。

关于为什么把Users改成me还是失败的问题。你使用client credential flow做认证请求图api,你只需要提供clientIdtenantIdclientSecret的信息。所以它不包含用户(或你自己)的信息。所以你不能使用.Me。如果要使用.Me,可以使用password grant flow。它包含用户信息,所以系统知道谁是.Me

==================================更新== ============================

如果要使用委托权限(如User.ReadBasic.All),则不能使用client_credential。现在您的代码使用 client_credential 流,访问令牌不包含用户身份。我在下面提供了一个 username/password 流程示例(并使用委托权限 User.ReadBasic.All)供您参考:

在注册应用的“API权限”选项卡中,我只添加了一个权限User.ReadBasic.All

代码如下:

using Microsoft.Graph;
using Microsoft.Graph.Auth;
using Microsoft.Identity.Client;
using System;
using System.Security;

namespace ConsoleApp3
{
    class Program
    {
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
            .Create("<clientId>")
            .WithTenantId("<tenantId>")
            .Build();

            string[] scopes = new string[] { "https://graph.microsoft.com/.default" };

            UsernamePasswordProvider authProvider = new UsernamePasswordProvider(publicClientApplication, scopes);

            GraphServiceClient graphClient = new GraphServiceClient(authProvider);

            var str = "<your password>";
            var password = new SecureString();
            foreach (char c in str) password.AppendChar(c);

            var users = await graphClient.Users.Request().WithUsernamePassword("<your account/email>", password).GetAsync();

            Console.WriteLine(users.Count);
        }
    }
}

并且在运行代码之前,您需要做一次“同意使用该应用程序”。您需要在浏览器中这样浏览 url:https://login.microsoftonline.com/<tenantId>/oauth2/v2.0/authorize?client_id=<clientId>&response_type=code&redirect_uri=<redirectUri>&response_mode=query&scope=openid https://graph.microsoft.com/.default&state=12345,页面将显示为:

点击“接受”,即可运行获取用户列表成功的代码