Getting invalid credentials error while creating user in windows active directory from azure app service

Sneha N. Patil 0 Reputation points
2023-09-22T09:07:19.39+00:00

I am trying below code to create new user in windows active directory. This code is working fine on local as well as when hosted on virtual machine. But same code is giving invalid credentials error when hosted on azure app service.

using (
            var pc = new PrincipalContext(ContextType.Domain, Domain, DefaultContainerKey, UserName, UserPassword))
        {
            using (var userPrincipal = new UserPrincipal(pc))
            {
                userPrincipal.Surname = lastName;
                userPrincipal.GivenName = firstName;
                userPrincipal.EmailAddress = emailAddress;
                userPrincipal.SamAccountName = userLogonName;
                userPrincipal.UserPrincipalName = string.Format("{0}@{1}", userLogonName, Domain);
                userPrincipal.DisplayName = $"{userPrincipal.GivenName} {userPrincipal.Surname}".Trim();
                userPrincipal.SetPassword(password);
                userPrincipal.Enabled = true;
                try
                {
                    userPrincipal.Save();
                    return true;
                }
                catch (Exception exception)
                {
                    _logger.Error("Exception creating user object. " + exception);
                    throw;
                }
            }
        }


Can someone please help me to understand why this is happening

Active Directory
Active Directory
A set of directory-based technologies included in Windows Server.
6,540 questions
Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
7,770 questions
{count} votes

2 answers

Sort by: Most helpful
  1. brtrach-MSFT 16,356 Reputation points Microsoft Employee
    2023-09-25T03:15:57.0433333+00:00

    @Sneha N. Patil Please note that I primarily deal with Azure Web Apps and this error seems to be more related to AAD. I will try my best to assist you, but I ask for your patience.

    It seems that you are getting an invalid credentials error while creating a new user in Windows Active Directory from Azure App Service. This error usually occurs when the credentials provided to connect to the Active Directory are incorrect or the user does not have sufficient permissions to create a new user.

    You can try the following steps to resolve the issue:

    Make sure that the credentials you are using to connect to the Active Directory are correct. You can try resetting the password and then use the new password to connect.

    Check if the user account you are using to connect to the Active Directory has sufficient permissions to create a new user. You can try using an account with higher privileges or grant the required permissions to the existing account.

    Make sure that the firewall rules are configured correctly to allow traffic from Azure App Service to the Active Directory.

    Check if the domain name and container key are correct. You can try using the fully qualified domain name (FQDN) of the domain instead of the short name.

    If the issue persists, you can check the Azure App Service logs for more details about the error. You can also try using the Azure Active Directory Graph API to create a new user instead of using the PrincipalContext class.


  2. brtrach-MSFT 16,356 Reputation points Microsoft Employee
    2023-10-18T16:05:31.0033333+00:00

    @Sneha N. Patil The Azure Active Directory Graph API is used to manage users and groups in Azure Active Directory, which is a cloud-based identity and access management service. It cannot be used to manage users in on-premises Windows Active Directory.

    Regarding the use of PrincipalContext to create a user in Windows Active Directory from Azure App Service, it should work as long as the credentials and permissions are correct and the firewall rules are configured correctly.

    Since you have confirmed that the user has the required permissions to create a user and the code works fine on your local machine, it is possible that the issue is related to the firewall rules. Please check the firewall rules to ensure that traffic from Azure App Service to the Active Directory is allowed.

    If the issue persists, you can try enabling diagnostic logging in Azure App Service to get more details about the error. You can also try using the LDAP protocol to connect to the Active Directory instead of the default Kerberos protocol used by PrincipalContext.

    Enabling diagnostic logging in Azure App Service:

    1. Go to the Azure portal and navigate to your App Service.
    2. Click on "App Service logs" under the Monitoring section.
    3. Turn on "Application Logging (Filesystem)" and "Detailed error messages".
    4. Save the changes and restart your App Service.

    This will enable diagnostic logging for your App Service, which should provide more details about the error you are encountering.

    Using the LDAP protocol to connect to Windows Active Directory:

    1. Replace the PrincipalContext constructor with the following code:
    var ldapPath = string.Format("LDAP://{0}", Domain);
    using (var context = new DirectoryEntry(ldapPath, UserName, UserPassword))
    {
        using (var user = context.Children.Add(string.Format("CN={0}", userLogonName), "user"))
        {
            user.Properties["samAccountName"].Value = userLogonName;
            user.Properties["userPrincipalName"].Value = string.Format("{0}@{1}", userLogonName, Domain);
            user.Properties["displayName"].Value = $"{firstName} {lastName}".Trim();
            user.Properties["givenName"].Value = firstName;
            user.Properties["sn"].Value = lastName;
            user.CommitChanges();
            user.Invoke("SetPassword", new object[] { password });
            user.CommitChanges();
            user.Properties["userAccountControl"].Value = 0x200;
            user.CommitChanges();
            return true;
        }
    }
    
    

    This code uses the DirectoryEntry class to connect to the Active Directory using the LDAP protocol. The Children.Add method is used to create a new user object, and the Properties collection is used to set the user's properties. The Invoke method is used to set the user's password, and the userAccountControl property is set to enable the user account.

    Please note that using the LDAP protocol may require additional configuration, such as opening the LDAP port on the firewall and configuring SSL/TLS encryption.

    If you find the above information helpful, we would appreciate you to provide a new survey or to accept this reply as an answer. This will help us recover the previous survey. If there is anything else we can do, please let us know.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.