如何使用AD帐户对我的应用程序进行“身份验证”? c#

问题描述 投票:0回答:2

我对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.
}

这只是告诉我该帐户当然是正确的,但是我的应用程序没有经过“认证”,有什么想法吗?

c# active-directory user-accounts
2个回答
0
投票

您可以通过使用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
}

0
投票

不能说您的“应用程序”已通过身份验证。已通过身份验证的只是与域控制器的单个网络连接。 _entry被销毁后,您将失去该身份验证。

如果您希望使用这些凭据来完成所有事情,那么您可以选择几种方法,从简单(对您来说)到更困难:

  1. 让您的用户以所需的凭据运行您的应用程序。然后,您无需费心获取其用户名和密码,也无需在DirectoryEntry对象上设置用户名和密码。用户可以通过以下方式执行此操作:

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

  3. 在应用程序的生命期内保持Process.Start()username变量有效,并将其传递给您在应用程序中创建的每个password对象。

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

© www.soinside.com 2019 - 2024. All rights reserved.