如何登录Active Directory?

时间:2012-07-26 08:22:12

标签: c# .net-4.0 active-directory authorization windows-server

我有活动目录的用户名和密码,我想使用C#登录到活动目录。我如何在Windows窗体中执行此操作?

4 个答案:

答案 0 :(得分:4)

解决方案

连接到Active Directory非常简单。

您必须使用DirectoryEntry对象(在命名空间System.DirectoryServices中)。

此对象的构造函数在参数中包含三个字符串:

  • Active Directory的路径。此路径的格式为:LDAP://your-name-AD
  • 连接的用户名
  • 相应的密码

实施例

using System.DirectoryServices;

try
{
   DirectoryEntry Ldap = new DirectoryEntry("LDAP://your-name-AD", "Login", "Password");
}
catch(Exception Ex)
{
   Console.WriteLine(Ex.Message);
}

答案 1 :(得分:4)

这个问题来自几年前,我希望这个答案可以在将来帮助人们。 这对我有用:

添加以下参考:

  • 使用System.DirectoryServices;
  • 使用System.DirectoryServices.AccountManagement;

之后,您可以在应用中使用此代码:

   PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOUR DOMAIN");
   bool Valid = pc.ValidateCredentials("User", "password");

名为有效的变量,如果logIn为Ok,则会显示 True 值。

有关详细信息,请访问this page。该页面来自此处, stackOverFlow ,它将显示有关以下内容的大量信息:“使用MS Active Directory登录”

答案 2 :(得分:2)

你去吧。此方法针对Active Directory验证username/password,并且在很长一段时间内一直是我的函数工具箱的一部分。

//NOTE: This can be made static with no modifications
public bool ActiveDirectoryAuthenticate(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();
            result = true;
        }
        catch
        { /* Error handling omitted to keep code short: remember to handle exceptions !*/ }
    }

    return result; //true = user authenticated!
}

执行此操作的软件必须在域内的计算机上运行,​​显然(或者您没有Active Directory来验证您的凭据)。

答案 3 :(得分:0)

较短的答案是添加参考 System.DirectoryServices.AccountManagement

然后使用 UserPrincipal.Current.Context.ValidateCredentials(“username”,“password”);

但我想您需要加入要验证的域名。