Search code examples
c#.netazure-active-directorymicrosoft-graph-api

Which Permission is required for Creating a New User in Microsoft using Graph API in C#


I Have a all permission like User.ReadWrite.All , Directory.ReadWrite.All and this permission type is Application.

I think something is Permission issue in this case, I want to Create a New User using this c# code.

and I get this error when i was trying to create a new user: the expression cannot be evaluated. A common cause of this error is attempting to pass a lambda into a delegate.

public async Task createNewUser()
{
    try
    {
        var requestBody = new User
        {
            AccountEnabled = true,
            City = "Surat",
            Country = "India",
            Department = "IT",
            DisplayName = "Test User Unknown",
            GivenName = "Unknown",
            JobTitle = "SharePoint Developer",
            MailNickname = "UnknownT",
            PasswordPolicies = "DisablePasswordExpiration",
            PasswordProfile = new PasswordProfile
            {
                Password = "0296db04-e2c3-cbec-993b-663e59e50f1c",
                ForceChangePasswordNextSignIn = false,
            },
            OfficeLocation = "131/1105",
            PostalCode = "395010",
            PreferredLanguage = "en-US",
            State = "Gujarat",
            StreetAddress = "9256 Towne Center Dr., Suite 400",
            Surname = "Test",
            MobilePhone = "+91 1324567891",
            UsageLocation = "India",
            UserPrincipalName = "[email protected]",
        };
        var result = await GraphClient.Users.PostAsync(requestBody);
        Console.WriteLine("User Created Successfully.");
    }
    catch (ServiceException ex)
    {
        Console.WriteLine($"Error getting user details: {ex.Message}");
    }
}```

Solution

  • To create user, make sure to grant User.ReadWrite.All application tpye API permission:

    enter image description here

    To create the user with the request body you provided, make use of below code:

    UsageLocation must be IN not as India

    using System;
    using System.Threading.Tasks;
    using Microsoft.Graph;
    using Azure.Identity;
    using Microsoft.Graph.Models.ODataErrors;
    using Microsoft.Graph.Models;
    
    namespace UserProperties
    {
        public class GraphHandler
        {
            public GraphServiceClient GraphClient { get; set; }
    
            public GraphHandler(string tenantId, string clientId, string clientSecret)
            {
                GraphClient = CreateGraphClient(tenantId, clientId, clientSecret);
            }
    
            public GraphServiceClient CreateGraphClient(string tenantId, string clientId, string clientSecret)
            {
                var options = new TokenCredentialOptions
                {
                    AuthorityHost = Azure.Identity.AzureAuthorityHosts.AzurePublicCloud
                };
    
                var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
                var scopes = new[] { "https://graph.microsoft.com/.default" };
    
                return new GraphServiceClient(clientSecretCredential, scopes);
            }
    
            public async Task<bool> CreateUser(User user)
            {
                try
                {
                    await GraphClient.Users.PostAsync(user);
                    Console.WriteLine("User created successfully.");
                    return true;
                }
                catch (ODataError odataError)
                {
                    Console.WriteLine($"OData error details:");
                    Console.WriteLine($"Code: {odataError.Error?.Code}");
                    Console.WriteLine($"Message: {odataError.Error?.Message}");
                    throw;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"An error occurred: {ex.Message}");
                    return false;
                }
            }
        }
    
        class Program
        {
            static async Task Main(string[] args)
            {
                try
                {
                    var tenantId = "TenantID";
                    var clientId = "ClientID";
                    var clientSecret = "ClientSecret";
                    var handler = new GraphHandler(tenantId, clientId, clientSecret);
    
                    var requestBody = new User
                    {
                        AccountEnabled = true,
                        City = "Surat",
                        Country = "India",
                        Department = "IT",
                        DisplayName = "Test User Unknown",
                        GivenName = "Unknown",
                        JobTitle = "SharePoint Developer",
                        MailNickname = "UnknownT",
                        PasswordPolicies = "DisablePasswordExpiration",
                        PasswordProfile = new PasswordProfile
                        {
                            Password = "***",
                            ForceChangePasswordNextSignIn = false,
                        },
                        OfficeLocation = "131/1105",
                        PostalCode = "395010",
                        PreferredLanguage = "en-US",
                        State = "Gujarat",
                        StreetAddress = "9256 Towne Center Dr., Suite 400",
                        Surname = "Test",
                        MobilePhone = "+91 1324567891",
                        UsageLocation = "IN",
                        UserPrincipalName = "[email protected]",
                    };
    
                    await handler.CreateUser(requestBody);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"An error occurred: {ex.Message}");
                }
            }
        }
    }
    

    enter image description here

    User created successfully with all the properties:

    enter image description here

    I modified the code to print ODataErrors so that it will be easy to identity the error.