简体   繁体   中英

C# Console App to Create User in Azure Active Directory using Microsoft Graph

How can I create an user in Azure AD using Microsoft Graph without having to login (from a console/service)?

It seams all the examples out there are so that you have to login first using AD account.

With this I get access denied.

class Program {
    static void Main (string[] args) {

        Create ().Wait ();
        Console.ReadLine ();
    }

    private static async Task Create () {
        var graph = new GraphServiceClient (new AzureAuthenticationProvider ());
        try {
            var users = await graph.Users.Request ().GetAsync ();
            int requestNumber = 1;
            while (users.Count > 0) {
                Console.WriteLine ("Request number: {0}", requestNumber++);
                foreach (var u in users) {
                    Console.WriteLine ("User: {0} ({1})", u.DisplayName,
                        u.UserPrincipalName);
                }

                if (users.NextPageRequest != null) {
                    users = await users.NextPageRequest.GetAsync ();
                } else {
                    break;
                }
            }
        } catch (ServiceException x) {
            Console.WriteLine ("Exception occured: {0}", x.Error);
        }
    }

}

public class AzureAuthenticationProvider : IAuthenticationProvider {
    public async Task AuthenticateRequestAsync (HttpRequestMessage request) {

        string clientId = "IDHERE";
        string clientSecret = "SECRETHERE";

        string tenantName = "somedomain.com";
        string authString = "https://login.microsoftonline.com/" + tenantName;

        AuthenticationContext authContext = new AuthenticationContext (authString, false);

        ClientCredential creds = new ClientCredential (clientId, clientSecret);

        AuthenticationResult authResult = await authContext.AcquireTokenAsync ("https://graph.microsoft.com/", creds);

        request.Headers.Add ("Authorization", "Bearer " + authResult.AccessToken);
    }
}

OK, So here it is! I spent half day to figure out this and now it works.

Go to Azure Portal -> AD Section -> Register New App (Web App / API), Create new Key and save it.

Required Permissions:

  • Application Permissions
    • Read and write directory data
  • Delegate Permissions (i think this doesn't matter)
    • Access the directory as the signed-in user
    • Read all users basic profile
    • Sign in and read user profile

Then from the Required Permissions blade click Grant Permissions at the top menu close to + Add button.

Then the code is like this:

  class Program
{
    static void Main(string[] args)
    {

        Create().Wait();
        Console.ReadLine();
    }


    private static async Task Create()
    {
        var graph = new GraphServiceClient(new AzureAuthenticationProvider());
        try
        {
            var users = await graph.Users.Request().GetAsync();
            int requestNumber = 1;
            while (users.Count > 0)
            {
                Console.WriteLine("Request number: {0}", requestNumber++);
                foreach (var u in users)
                {
                    Console.WriteLine("User: {0} ({1})", u.DisplayName,
                        u.UserPrincipalName);
                }

                if (users.NextPageRequest != null)
                {
                    users = await users.NextPageRequest.GetAsync();
                }
                else
                {
                    break;
                }
            }
        }
        catch (ServiceException x)
        {
            Console.WriteLine("Exception occured: {0}", x.Error);
        }
    }

}

internal class AppModeConstants
{
    public const string ClientId = "YOUR_CLIENT_ID_HERE";
    public const string ClientSecret = "YOUR_SECRET_HERE";
    public const string TenantName = "YOUR_TENANT_NAME_HERE";  //somedomain.com
    public const string TenantId = "YOUR_TENANT_ID_HERE";
    public const string AuthString = GlobalConstants.AuthString + TenantName;
}


internal class GlobalConstants
{
    public const string AuthString = "https://login.microsoftonline.com/";
    public const string ResourceUrl = "https://graph.microsoft.com";
    public const string GraphServiceObjectId = "00000002-0000-0000-c000-000000000000";
}

public class AzureAuthenticationProvider : IAuthenticationProvider
{
    public async Task AuthenticateRequestAsync(HttpRequestMessage request)
    {         


        AuthenticationContext authContext = new AuthenticationContext(AppModeConstants.AuthString,false);

        ClientCredential creds = new ClientCredential(AppModeConstants.ClientId, AppModeConstants.ClientSecret);

        AuthenticationResult authResult = await authContext.AcquireTokenAsync(GlobalConstants.ResourceUrl,creds);

        request.Headers.Add("Authorization", "Bearer " + authResult.AccessToken);
    }
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM