Microsoft Graph - 使用 Graph SDK 代码库获取特定用户及其 AD 组成员资格

Microsoft Graph - getting a specific user and his AD group memberships using the Graph SDK code base

尝试使用 Microsoft Graph API 来处理在我们的 MS 云中查找数据 - 但我被卡住了。有这么多文档 - 但从来没有正确的文档....

我正在尝试使用 C# Graphi 客户端 SDK,我正在尝试读取给定用户的详细信息,包括其 AD 组成员资格。

我已经在 Azure AD 中注册了我的应用程序,我能够启动 IPublicClientApplication 并且 运行 并且身份验证也有效:

IPublicClientApplication app = PublicClientApplicationBuilder
                                       .Create(clientId)
                                       .WithTenantId(tenantId)
                                       .Build();

UsernamePasswordProvider authProvider = new UsernamePasswordProvider(app, scopes);

// creating Graph SDK client 
GraphServiceClient graphClient = new GraphServiceClient(authProvider);

string userName = "......";
var securePassword = new SecureString();

// filling secure password here.....

var users = graphClient.Users
                       .Request()
                       .WithUsernamePassword(userName, securePassword)
                       .Filter("userPrincipalName eq 'someone@myorg.com'")
                       .GetAsync().Result;

这有效 - 我确实取回了有关过滤器中指定用户的基本用户详细信息。

两件事:

  1. 我不喜欢这样的事实,我似乎必须在每次调用客户端时都添加 .WithUsernamePassword - 没有办法将该信息包含在 graphClient 一次并完成它,直到我注销?

  2. 我正在尝试获取群组成员资格。我可以通过在我的查询字符串中添加 /MemberOf 在 Graph Explorer 中执行此操作 - 但我无法在 Graph SDK 客户端场景中使用它。

我看到很多博客展示了如何使用

获取 当前登录用户的
graphClient.Me.MemberOf.Request().GetAsync();

但我不想要 我的 组成员资格 - 我想要我在搜索过滤器中指定的用户的成员资格,如上所示。

尝试简单地添加 .Expand("memberOf") 似乎没有帮助 - 返回的用户对象在其 MemberOf 属性.

中仍然没有值

我错过了什么?我不敢相信这会如此棘手和困难??还是我真的需要重新对 REST API 发出 HTTP GET 请求??如果 MS 提供 SDK 和客户端代码似乎很奇怪.....坦率地说,我更愿意使用它。

要获得特定用户的会员资格,您可以像这样拨打电话

await client.Users["username@domain.com"].MemberOf.Request().GetAsync();

您可以遍历用户列表并将上面代码段中的 username@domain.com 替换为 user.UserPrincipalName 属性。

您也可以使用不同的提供者,这样您只需提供一次凭据,并且在应用程序的整个生命周期内使用。例如,下面的代码使用 InteractiveAuthenticationProvider,这将创建一个浏览器弹出窗口,您将登录一次,您的凭据将用于您应用中的其余请求。

IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
    .Create(clientId)
    .WithRedirectUri("http://localhost:1256")
    .Build();

InteractiveAuthenticationProvider authProvider = new InteractiveAuthenticationProvider(publicClientApplication, scopes);

GraphServiceClient client = new GraphServiceClient(authProvider);

var users = await client.Users.Request().GetAsync();

foreach (var user in users)
{
    var result = await client.Users[user.UserPrincipalName].MemberOf.Request().GetAsync();
}

您可以根据您的情况将此页面用作一堆身份验证提供程序的参考。 https://docs.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=CS