【问题标题】:C# access Active Directory as another userC# 以另一个用户身份访问 Active Directory
【发布时间】:2019-05-13 18:31:32
【问题描述】:

我想就以下问题寻求您的帮助。我正在开发临时应用程序,仅由我使用一次。

其中一部分是为 AD 中的 3000 多个用户执行密码重置并向他们发送新凭据。

我可以以普通用户的身份从 AD 读取,但我必须使用特权帐户来修改它。我怎样才能做到这一点?我知道,我可以使用 PowerShell 并在几秒钟内完成,但我想学习如何在 C# 中完成它。

我搜索用户的代码很简单

public class ADSecurity
{
    public static string getUserName(string sam)
    {
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
        UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, sam);
        return user.Name;
    }
}

作为不同的用户,我该如何做同样的事情?

我看过一些指南,但都没有解释 a-z ... 只是关于如何模仿的建议,但没有关于如何使用它的建议。这里有一篇关于模拟的文章,但使用的是 LDAP 协议 (DirectoryEntry)。但据我了解,它真的很慢。

任何建议表示赞赏。我需要从现在开始 2 天后运行它,所以在最坏的情况下,我使用 PowerShell 来完成它。

谢谢。

【问题讨论】:

    标签: c# active-directory impersonation


    【解决方案1】:

    有几种方法可以做到:

    1. 在所需凭据下运行您的应用程序(Shift+右键单击 .exe 文件并使用“以其他用户身份运行”)。如果您只执行一次,这是最简单的。
    2. 使用接受用户名和密码的PrincipalContext constructor
    public class ADSecurity
    {
        public static string getUserName(string sam)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain, null, username, password);
            UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, sam);
            return user.Name;
        }
    }
    
    1. 使用接受用户名和密码的DirectoryEntry constructor

    我不确定您说的哪个示例“慢”,但根据我的经验,只要您正确使用它,直接使用DirectoryEntry 几乎总是更快。 System.DirectoryServices.AccountManagement 命名空间(您在示例中使用的)在幕后使用 DirectoryEntry

    当然,选项 2 和 3 要求您知道密码。

    【讨论】:

    • 选项 2 看起来完全符合我的要求。从我读到的有关 System.DirectoryServices.AccountManagement 的内容中,我并不是很明智,但显然,我应该更深入地研究。 :-) P.S:我们公司对账目有严格的规定。使用我的特权帐户,我可以从技术上“擦除”域,但不能使用它来运行任何应用程序、服务、计划任务或登录任何计算机。 P.P.S:Thaaaaaaanks!
    猜你喜欢
    • 2012-06-28
    • 2021-04-25
    • 1970-01-01
    • 2018-09-21
    • 2019-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多