LDAP 全称是 Lightweight Directory Access Protocol,中文名称:轻型目录访问协议,广泛用于统一认证。
下面实现了简单的用户名、密码验证:
using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices.Protocols;
using System.Net;
namespace com.hetaoos.Authenticator
{
/// <summary>
/// Ldap 验证
/// http://blog.hetaoos.com
/// </summary>
public class LdapAuthenticator
{
/// <summary>
/// Ldap 验证
/// </summary>
/// <param name="domain">服务器</param>
/// <param name="username">帐号</param>
/// <param name="pwd">密码</param>
/// <returns>是否验证成功</returns>
public static bool ValidateUser(string domain, string userName, string password)
{
bool validation = false;
LdapConnection ldc = null;
try
{
ldc = new LdapConnection(domain);
//ou=Users,ou=tempusers,ou=staff,dc=guet,dc=org 这串玩意要改为自己的
NetworkCredential nc = new NetworkCredential(string.Format("uid={0},ou=Users,ou=tempusers,ou=staff,dc=guet,dc=org", userName), password);
ldc.AuthType = AuthType.Basic;
ldc.SessionOptions.ProtocolVersion = 3;
ldc.Bind(nc);
validation = true;
}
catch { }
finally
{
if (ldc != null)
{
ldc.Dispose();
}
}
return validation;
}
}
}
PS:
需要添加以下引用:
1,System.DirectoryServices
2,System.DirectoryServices.Protocols
调用很简单:
bool authenticated = LdapAuthenticator.ValidateUser("ldap.hetaoos.com", "null", "hetaoos.com");


最近评论