This post should have appeared before the other related posts. However let us see from the ground up how we can build an application to use Azure AD Graph API to add the user to AAD.
We first need to add an application in AAD
Open the Azure AD in portal and open the application tab, click to add new
Then
If this is a properly hosted web application then give that URL else for desktop application can give any well formatted dully URL
Now go to the Azure AD Application’s Configuration tab,
Copy the Client ID
Then under Keys add a new Key and copy after you click Save. This is visible for one time. Later point in time you will not see it.
Go to the permissions to other applications section and add required permissions
Then copy the App End Point
Then create a Windows Application
const
string authString = “https://login.windows.net/fc46a878-eaec-45f4-b55d-569ed059110”;
const
string appClientID = ” fc46a878-eaec-45f4-b55d-569ed059110″;
const
string appClientSecret = “hd1EKxvACeG5ocaUcKsHGDglOKtLpOHGzeVU46+TrT4=”;
const
string resAzureGraphAPI = “https://graph.windows.net”;
const
string serviceRootURL = “https://graph.windows.net/fc46a878-eaec-45f4-b55d-569ed059110”;
private
static
async
Task<string> GetAppTokenAsync()
{
AuthenticationContext authenticationContext = new
AuthenticationContext(authString, false);
ClientCredential clientCred = new
ClientCredential(appClientID, appClientSecret);
AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(resAzureGraphAPI, clientCred);
return authenticationResult.AccessToken;
}
private
ActiveDirectoryClient GetAADClient()
{
Uri serviceRoot = new
Uri(serviceRootURL);
ActiveDirectoryClient adClient = new
ActiveDirectoryClient(
serviceRoot,
async () => await GetAppTokenAsync());
return adClient;
}
private
async
Task CreateUser()
{
var adClient = GetAADClient();
//Construct the User
string userEmail = “wriju.ghosh@Microsoft.com”;
string mailNickname = userEmail.Split(new
char[] { ‘@’ }).FirstOrDefault();
var userGraphObj = new Microsoft.Azure.ActiveDirectory.GraphClient.User()
{
GivenName = “Wriju”,
Surname = “Ghosh”,
Mobile = “1234567890”,
MailNickname = mailNickname,
DisplayName = “Wriju.Test”,
AccountEnabled = true
};
userGraphObj.OtherMails.Add(userEmail);
string tenantName = “wgad.onmicrosoft.com”;
var userPrincipleName = “test_” + Guid.NewGuid().ToString() + “@” + tenantName;
userGraphObj.UserPrincipalName = userPrincipleName;
var tempPassword = Membership.GeneratePassword(8, 1);
var passwordProfile = new
PasswordProfile
{
Password = tempPassword,
ForceChangePasswordNextLogin = true
};
userGraphObj.PasswordProfile = passwordProfile;
adClient.Users.AddUserAsync(userGraphObj);
txtMSG.Text = @”User Created” + Environment.NewLine + userPrincipleName + Environment.NewLine + tempPassword;
}
Let me thank the most comprehensive blog at https://www.simple-talk.com/cloud/security-and-compliance/azure-active-directory-part-5-graph-api/
Namoskar!!!