Reputation: 884
I have a requirement to create user or group in azure active directory programmatically. I searched on google and I found multiple solutions like using Graph APIs, C# Code etc.. but I am bit confused with the approach.
Can any one help me out with the difference between these approaches and suggest me the best approach? Please let me know if there are any code samples available.
Thanks in advance !!
Upvotes: 1
Views: 2034
Reputation: 14649
Azure ad support multiple protocols. To acquire the token for the Azure AD Graph we need to choose the suitable flow in OAuth 2.0/OpenId connect to interact with Azure AD.
For example, if you were developing a web app the OAuth code grant flow maybe is a good choice. And if the app is daemon app or service application, the client credentials flow the better one. More about the scenarios you can refer this document.
And to acquire the token for Azure AD Graph in a web app, you can refer this code sample. At the line of 104 of this code sample, it acquire the access token for Azure AD Graph. And then in the controller, you can use the code below to acquire the token from cache and create the user using Azure AD Graph:
string graphResourceId = "https://graph.windows.net";
string tenantId = "xxx.onmicrosoft.com";
AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/xxx.onmicrosoft.com");
ClientCredential credential = new ClientCredential("{clientId}", "{secret}");
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationResult result = await authContext.AcquireTokenSilentAsync(graphResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
var accessToken = result.AccessToken;
Uri servicePointUri = new Uri(graphResourceId);
Uri serviceRoot = new Uri(servicePointUri, tenantId);
ActiveDirectoryClient graphClient = new ActiveDirectoryClient(serviceRoot, async () => await Task.FromResult(accessToken));
var user = new User();
user.AccountEnabled = true;
user.DisplayName = "testName";
user.UserPrincipalName = "[email protected]";
user.MailNickname = "testName";
user.UsageLocation = "US";
user.PasswordProfile = new PasswordProfile
{
Password = "xxxxxx",
ForceChangePasswordNextLogin = true
};
await graphClient.Users.AddUserAsync(user);
And the application requires Directory.ReadWrite.All
to create user and group. More detail about the permission you can refer here.
Upvotes: 1