Jay
Jay

Reputation: 280

Add users to active directory through user impersonation

I have a windows application, which allows app user to add/remove users into Active Directory group. Application users logins to application using their windows credentials. But, all the individual users doesn't have access to add/remove users in to AD group. I wanted to internally impersonate a user having modify permissions to AD group. I am using below code, I sourced it from different answers of SO. Not sure, if I am using it wrong. But I get an exception.

Using this library for impersonation: https://www.codeproject.com/Articles/10090/A-small-C-Class-for-impersonating-a-User

using (new Impersonator("username", "domain", "passowrd"))
        {

            using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
            {
                // find your user
                UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "user");

                if (user != null)
                {
                    // find the group in question
                    GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "Group Name");

                    // if found....
                    if (group != null)
                    {
                        // add user to group
                        group.Members.Add(user);
                        group.Save();
                    }
                }
            }
        }

If I login using the user having proper permissions, I am able to add/remove users from AD. But not by impersonation.

Upvotes: 0

Views: 558

Answers (1)

Gabriel Luci
Gabriel Luci

Reputation: 41018

You don't need impersonation to connect to AD with different credentials. Just use the constructor for PrincipalContext that accepts a username and password:

using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, null, "username", "password"))

Upvotes: 1

Related Questions