简体   繁体   English

通过用户模拟将用户添加到活动目录

[英]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.我有一个 Windows 应用程序,它允许应用程序用户将用户添加/删除到 Active Directory 组中。 Application users logins to application using their windows credentials.应用程序用户使用他们的 Windows 凭据登录到应用程序。 But, all the individual users doesn't have access to add/remove users in to AD group.但是,所有个人用户都无权在 AD 组中添加/删除用户。 I wanted to internally impersonate a user having modify permissions to AD group.我想在内部模拟一个对 AD 组具有修改权限的用户。 I am using below code, I sourced it from different answers of SO.我正在使用下面的代码,我从 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使用此库进行模拟: 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.如果我使用具有适当权限的用户登录,则可以从 AD 添加/删除用户。 But not by impersonation.但不是通过冒充。

You don't need impersonation to connect to AD with different credentials.您不需要模拟来使用不同的凭据连接到 AD。 Just use the constructor for PrincipalContext that accepts a username and password :只需使用接受用户名和密码的PrincipalContext构造函数

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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