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



我有一个Windows应用程序,它允许应用程序用户在Active Directory组中添加/删除用户。应用程序用户使用其 Windows 凭据登录到应用程序。但是,所有单个用户都无权在 AD 组中添加/删除用户。我想在内部模拟对 AD 组具有修改权限的用户。我正在使用下面的代码,我从SO的不同答案中获取它。不确定,如果我用错了。但我有一个例外。

使用此库进行模拟: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();
}
}
}
}

如果我使用具有适当权限的用户登录,则可以在AD中添加/删除用户。但不是冒充。

无需模拟即可使用不同的凭据连接到 AD。只需对接受用户名和密码的PrincipalContext使用构造函数:

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

最新更新