如何使用 AD 帐户保持我的应用程序"authenticated"?c#



我对C#很陌生
我一直在使用Powershell脚本来编写解锁AD用户或启用/禁用帐户之类的代码。然而,我用一个不同的帐户来做这件事,所以我会用管理员帐户(Get-Credential(登录,并将其存储为"$cred"。

我目前正在尝试在C#中做类似的事情,我已经找到了如何有效地"身份验证"但我不知道如何存储该身份验证,也不知道如何对我的应用程序进行身份验证,以对其执行禁用或解锁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.
}

这只是告诉我账户当然是正确的,但没有保持我的申请"认证",有什么想法吗?

说您的"应用程序"已通过身份验证是不准确的。所有经过身份验证的都是到域控制器的单个网络连接。一旦_entry被销毁,您就失去了该身份验证。

如果你想使用这些凭据实现一切,那么你有几个选择,从简单(对你来说(到更困难:

  1. 让用户使用他们需要的凭据运行应用程序。然后,您就不需要麻烦地获取他们的用户名和密码,也不需要在DirectoryEntry对象上设置用户名和密码。用户可以通过以下方式进行操作:

    • 使用Shift键并右键单击应用程序图标,然后单击"以其他用户身份运行",或者
    • 创建一个快捷方式:runas.exe /user:DOMAINusername "yourapplication.exe"。这将打开一个命令窗口,询问密码,然后使用这些凭据启动应用程序
  2. 您仍然需要用户名和密码,但使用Process.Start()在这些凭据下重新启动应用程序。

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

选项1和2要求您运行此程序的计算机与您连接的域加入同一个或受信任的域。但由于我看到您没有指定域名,我猜是这样。

通过使用System.DirectoryServices.AccountManagement程序集和名称空间,可以更容易地完成这项工作。

将对System.DirectoryServices.AccountManagement程序集的引用添加到您的项目中,然后使用此代码根据AD:验证用户名/密码

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
}

最新更新