[英]How to fetch all users from Azure Active Directory Group using C#
We have an application developed in ASP.NET MVC.我们在 ASP.NET MVC 中开发了一个应用程序。 We also have Acitve Directory configured in Azure and it has some Groups into it.我们还在 Azure 中配置了 Acitve 目录,其中包含一些组。 Requirement is, we need to fetch all users from Azure Active Directory's Group and add a new user into it.要求是,我们需要从 Azure Active Directory 的组中获取所有用户并添加一个新用户。
We are using code below and it is asking extra authentication I guess.我们正在使用下面的代码,我猜它要求额外的身份验证。 we want to provide all authentication in code it self without giving popup wondow to authenticate.我们希望在它自己的代码中提供所有身份验证,而不需要弹出窗口进行身份验证。 Can you please help with this你能帮忙吗
// 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();
Above code shows a message as "To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code G9277ULC9 to authenticate."上面的代码显示一条消息“要登录,请使用 web 浏览器打开页面https://microsoft.com/devicelogin并输入代码 G9277ULC9 进行身份验证。”
How can we provide all authentication information in code itself to avoid this step?我们如何在代码本身中提供所有身份验证信息以避免此步骤?
Updated API permissions are as below -更新的 API 权限如下 -
You could use the Microsoft Graph SDK to do that.您可以使用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);
Update :更新:
If you want a non-interactive way, you need to use the client credential flow, ie create the authProvider
instance as Client credentials provider .如果您想要一种非交互方式,您需要使用客户端凭据流,即创建authProvider
实例作为客户端凭据提供程序。
IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantID)
.WithClientSecret(clientSecret)
.Build();
ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.