问题
We have an application developed in ASP.NET MVC. We also have Acitve Directory configured in Azure and it has some Groups into it. Requirement is, we need to fetch all users from Azure Active Directory's Group and add a new user into it.
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."
How can we provide all authentication information in code itself to avoid this step?
Updated API permissions are as below -
Thank you in advance.
回答1:
You could use the Microsoft Graph SDK to do that.
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, i.e. create the authProvider instance as Client credentials provider.
IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithTenantId(tenantID)
    .WithClientSecret(clientSecret)
    .Build();
ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
来源:https://stackoverflow.com/questions/58212958/how-to-fetch-all-users-from-azure-active-directory-group-using-c-sharp