c# - 如何使用 C# 从 Azure Active Directory 组获取所有用户

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

我们有一个使用 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 权限如下 -

enter image description here 预先感谢您。

最佳答案

您可以使用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);

关于c# - 如何使用 C# 从 Azure Active Directory 组获取所有用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58212958/

相关文章:

azure - 将 Azure RBAC 分配到资源组级别的 Azure AD 安全组

java - 如何使用 Java 下载/上传 Azure B2C TrustFrameworkPolicy

c# - 为什么在类中声明同名实例级静态字段时,方法作用域参数值会乱码

c# - 在 C# 中计算 future 纪元时间

azure - 如何找到 AKS 群集的服务主体 secret ?

azure - 使用哪种 Azure 监视服务来可视化组件之间的关系?

azure - 即使 Azure AD 租户为空,也无法删除

c# - 确定 WPF 元素类型

c# - Refit和Web API之间如何共享服务方法URL?

python - 调用 MS Graph API 收集在线 MS 表单响应