在.NET MVC中使用LDAP /网络凭据验证用户

时间:2012-01-17 13:38:44

标签: c# asp.net-mvc-3 ldap validation

我正在使用.NET中的MVC 3应用程序,我对LDAP没有太多经验,但我希望能够简单地验证用户是否存在。我不需要验证用户名和密码组合,如下例所示:

LDAP Authentication in ASP.Net MVC

虽然这几乎是我想要做的。我只需要在添加用户名之前验证用户名。

在.NET / MVC中有一种简单的方法吗

2 个答案:

答案 0 :(得分:5)

使用System.DirectoryServices.AccountManagement命名空间并通过更改IdentityType枚举来传递用户名或专有名称(例如CN = John Doe)。

public bool UserExists(string username) 
{ 
   PrincipalContext domain = new PrincipalContext(ContextType.Domain); 

   // locate the user
   UserPrincipal user = UserPrincipal.FindByIdentity(domain, IdentityType.Name, username); 

   return user != null; 
} 

答案 1 :(得分:3)

您可以使用LdapConnectionSearchRequest来实现这一目标。

获取所有用户的示例:

/// <summary>
/// Gets the LDAP users from the LDAP server.
/// </summary>
/// <param name="ldapServer">The LDAP server, string format: "LDAP://172.22.100.10:389/OU=AT,O=ON"</param>
/// <param name="directoryType">Type of the directory.</param>
/// <param name="user">The user.</param>
/// <param name="password">The password.</param>
/// <param name="domain">The domain (AD only).</param>
/// <returns>String list of LDAP users.</returns>
public List<string> GetLdapUsers(string ldapServer, LocalDirectoryType directoryType, string user, string password, string domain)
{
    List<string> LdapUsers = new List<string>();

    string serverName = Regex.Match(ldapServer, @"^.+//(.+?):").Groups[1].ToString();
    string distinguishedName = ldapServer.Substring(ldapServer.LastIndexOf("/") + 1);

    LdapConnection connection = new LdapConnection(new LdapDirectoryIdentifier(serverName));
    switch (directoryType)
    {
        case LocalDirectoryType.ActiveDirectory:
            connection.AuthType = AuthType.Ntlm;
            break;
        case LocalDirectoryType.eDirectory:
            connection.AuthType = AuthType.Basic;
            break;
    }

    // attempt to connect
    try { connection.Bind(new NetworkCredential(user, password)); }
    catch (Exception exception)
    {
        Trace.WriteLine(exception.ToString());
    }

    // run search for users
    SearchResponse response = connection.SendRequest(new SearchRequest(distinguishedName, "(|(objectClass=person)(objectClass=user))", System.DirectoryServices.Protocols.SearchScope.Subtree, null)) as SearchResponse;

    // extract users from results based on server type
    if (directoryType == LocalDirectoryType.ActiveDirectory)
    {
        foreach (SearchResultEntry entry in response.Entries)
        {
            if (entry.Attributes.Contains("sAMAccountName") && entry.Attributes["sAMAccountName"][0].ToString() != String.Empty)
                LdapUsers.Add(domain + "\\" + entry.Attributes["sAMAccountName"][0].ToString());
        }
    }
    else
    {
        foreach (SearchResultEntry entry in response.Entries)
        {
            if (entry.Attributes.Contains("cn") && entry.Attributes["cn"][0].ToString() != String.Empty)
            {
                LdapUsers.Add("cn=" + entry.Attributes["cn"][0].ToString());
            }

        }
    }

    return LdapUsers;
}