Hi @Pappu Singh
Do not use the common
endpoint in the client credentials flow, or your token will not contain the target tenant's information, because the client credentials flow is an unattended authentication flow.
If you want to use the client credentials flow to create users for the target tenant, you first need to add your multi-tenant application as an enterprise application to the target tenant. You can run the admin consent URL in the browser, then log in with the target tenant's admin and accept.
https://login.microsoftonline.com/{the tenant-id of the target tenant}/adminconsent?client_id={client-id}
Next, you need to set the value of the tenantId
variable to the tenant id or domain name of the target tenant:
var tenantId = "{the tenant id or domain name of the target tenant}";
Refer to the complete sample code:
using Azure.Identity;
using Microsoft.Graph;
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "{the tenant id or domain name of the target tenant}";
// Values from app registration
var clientId = "{client id}";
var clientSecret = "{client secret}";
// using Azure.Identity;
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
// https://learn.microsoft.com/dotnet/api/azure.identity.clientsecretcredential
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret, options);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var user = new User
{
AccountEnabled = true,
DisplayName = "xxxx",
MailNickname = "xxxx",
UserPrincipalName = "xxxxx@xxxxx.xxxxxxxxx",
PasswordProfile = new PasswordProfile
{
ForceChangePasswordNextSignIn = true,
Password = "xxxxxxxxx"
}
};
await graphClient.Users
.Request()
.AddAsync(user);
If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.