5

是否有可用的 Active Directory 助手类?在我重新发明轮子之前检查一下。

我需要

  1. 在 AD 中验证用户。

  2. 获取他/她的成员角色。

谢谢

4

3 回答 3

10

在 .NET 3.5 中,您想查看System.DirectoryServices.AccountManagement。对于较早的版本,System.DirectoryServices具有您需要的功能,但需要做更多的工作。

using (var context = new PrincipalContext( ContextType.Domain ))
{
      var valid = context.ValidateCredentials( username, password );
      using (var user = UserPrincipal.FindByIdentity( context,
                                                      IdentityType.SamAccountName,
                                                      username ))
      {
          var groups = user.GetAuthorizationGroups();
      }
}
于 2009-06-12T00:27:35.630 回答
3

这是我一直在使用的一些示例代码:

using System.DirectoryServices;

public static string GetProperty(SearchResult searchResult, 
    string PropertyName)
{
    if (searchResult.Properties.Contains(PropertyName))
        return searchResult.Properties[PropertyName][0].ToString();
    else
        return string.Empty;
}

public MyCustomADRecord Login(string UserName, string Password)
{
    string adPath = "LDAP://www.YourCompany.com/DC=YourCompany,DC=Com";

    DirectorySearcher mySearcher;
    SearchResult resEnt;

    DirectoryEntry de = new DirectoryEntry(adPath, UserName, Password, 
        AuthenticationTypes.Secure);
    mySearcher = new DirectorySearcher(de);

    string adFilter = "(sAMAccountName=" + UserName + ")";
    mySearcher.Filter = adFilter;

    resEnt = mySearcher.FindOne();


    return new MyCustomADRecord()
    {
        UserName = GetProperty(resEnt, "sAMAccountName"),
        GUID = resEnt.GetDirectoryEntry().NativeGuid.ToString(),
        DisplayName = GetProperty(resEnt, "displayName"),
        FirstName = GetProperty(resEnt, "givenName"),
        MiddleName = GetProperty(resEnt, "initials"),
        LastName = GetProperty(resEnt, "sn"),
        Company = GetProperty(resEnt, "company"),
        JobTitle = GetProperty(resEnt, "title"),
        Email = GetProperty(resEnt, "mail"),
        Phone = GetProperty(resEnt, "telephoneNumber"),
        ExtensionAttribute1 = GetProperty(resEnt, "extensionAttribute1")
    };
}
于 2009-06-12T00:30:30.007 回答
2

System.DirectoryServices.ActiveDirectory 命名空间

http://msdn.microsoft.com/en-us/library/system.directoryservices.activedirectory.aspx

于 2009-06-12T00:25:19.487 回答