【问题标题】:How to fetch all users from Azure Active Directory Group using C#如何使用 C# 从 Azure Active Directory 组中获取所有用户
【发布时间】:2020-02-01 09:48:14
【问题描述】:

我们有一个用 ASP.NET MVC 开发的应用程序。我们还在 Azure 中配置了 Acitve Directory,其中包含一些组。 要求是,我们需要从 Azure Active Directory 的组中获取所有用户并添加一个新用户。

我们正在使用下面的代码,我猜它要求额外的身份验证。我们希望在它自己的代码中提供所有身份验证,而不需要弹出窗口进行身份验证。你能帮忙吗

   // Build a client application.
            IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
                        .Create("clientID")
                        .WithTenantId("tenantId")
                        .Build();
            // Create an authentication provider by passing in a client application and graph scopes.
            DeviceCodeProvider authProvider = new DeviceCodeProvider(publicClientApplication, new[] { "User.Read" });
            // Create a new instance of GraphServiceClient with the authentication provider.
            GraphServiceClient graphClient = new GraphServiceClient(authProvider);

            var members = await graphClient.Groups["groupId"].Members
                .Request()
                .GetAsync();

上面的代码显示了一条消息 “要登录,请使用网络浏览器打开页面https://microsoft.com/devicelogin 并输入代码G9277ULC9 进行身份验证。”

我们如何在代码本身中提供所有身份验证信息以避免这一步?

更新 API 权限如下 -

提前谢谢你。

【问题讨论】:

  • 这不是问题。这是业务需求。你应该研究,尝试做一些事情,然后如果你有任何特定的代码问题,你可以问。但是代码在哪里?我没有看到。
  • @JohnB,我知道这可能不是正确的论坛。但不确定从哪里开始,因此在此处发布以获取少量参考。
  • @JohnB 代码现在可用,您能帮忙吗?

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


【解决方案1】:

您可以使用Microsoft Graph SDK 来执行此操作。

List members of a group:

GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var members = await graphClient.Groups["{id}"].Members
    .Request()
    .GetAsync();

Add member to a group:

GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var directoryObject = new DirectoryObject
{
    AdditionalData = new Dictionary<string, object>()
    {
        {"@odata.id","https://graph.microsoft.com/v1.0/directoryObjects/{id}"}
    }
};

await graphClient.Groups["{id}"].Members.References
    .Request()
    .AddAsync(directoryObject);

更新

如果您想要一种非交互方式,则需要使用客户端凭据流,即将authProvider 实例创建为Client credentials provider

IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithTenantId(tenantID)
    .WithClientSecret(clientSecret)
    .Build();

ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);

【讨论】:

猜你喜欢
  • 2023-01-26
  • 1970-01-01
  • 2018-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多