如何让我的应用程序 "authenticated" 使用 AD 帐户? C#

How to keep my application "authenticated" with an AD account? c#

我是 C# 的新手
我一直在使用 Powershell 脚本来编写诸如解锁 AD 用户或 Enabling/Disabling 帐户之类的代码。但是,我使用不同的帐户执行此操作,因此我将使用管理员帐户 (Get-Credential) 登录并将其存储为例如“$cred”。

我目前正尝试在 C# 中做类似的事情,我已经找到了如何有效地 "Authenticate" 但我不确定如何存储该身份验证,或者让我的应用程序经过身份验证以使用它执行禁用或解锁 AD 帐户等操作。

我有这个:

public bool ADauthenticate(string username, string password)
{
    bool result = false;
    using (DirectoryEntry _entry = new DirectoryEntry())
    {
        _entry.Username = username;
        _entry.Password = password;
        DirectorySearcher _searcher = new DirectorySearcher(_entry);
        _searcher.Filter = "(objectclass=user)";
        try
        {
            SearchResult _sr = _searcher.FindOne();
            string _name = _sr.Properties["displayname"][0].ToString();
            MessageBox.Show("authenticated!");
            result = true;
            this.Close();
        }
        catch
        {
            MessageBox.Show("Incorrect credentials");
            this.ADUsername.Text = "";
            this.ADPwd.Text = "";
        }
    }
    return result; //true = user Authenticated.
}

这只是告诉我帐户当然是正确的,但没有保留我的申请 "authenticated",有什么想法吗?

通过使用 System.DirectoryServices.AccountManagement 程序集和命名空间,您可以更轻松地做到这一点。

将对 System.DirectoryServices.AccountManagement 程序集的引用添加到您的项目中,然后使用此代码针对 AD:

验证 username/password
using System.DirectoryServices.AccountManagement;

// create the principal context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YourDomain"))
{
    bool accountValidated = ctx.ValidateCredentials(userName, password);

    // do whatever you want to do with this information
}

说您的 "application" 已通过身份验证是不准确的。所有经过身份验证的都是与您的域控制器的单一网络连接。一旦 _entry 被销毁,您将失去该身份验证。

如果您希望所有事情都使用这些凭据进行,那么您有多种选择,从简单(对您而言)到更困难:

  1. 让您的用户运行 在他们需要的凭据下使用您的应用程序。然后你就不需要费心去获取他们的用户名和密码,或者在 DirectoryEntry 对象上设置用户名和密码。用户可以通过:

    • 使用 Shift + 右键单击​​应用程序图标并单击 "Run as a different user",或
    • 创建快捷方式至:runas.exe /user:DOMAIN\username "yourapplication.exe"。这将打开一个命令 window 询问密码,然后在这些凭据下启动您的应用程序。
  2. 您仍然要求输入用户名和密码,但使用 Process.Start() 在这些凭据下重新启动您的应用程序。

  3. 在应用程序的生命周期内保持 usernamepassword 变量有效,并将它们传递给您在应用程序中创建的每个 DirectoryEntry 对象。

选项 1 和 2 要求您 运行 从中执行此操作的计算机已加入与您要连接的域相同或受信任的域。但是因为我看到你没有指定域名,所以我猜是这样的。