简体   繁体   中英

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.

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"))

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