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");
Did you like this? Share it:

关联文章:

  1. C# 中利用反射机制拷贝类的字段和属性
  2. C# 类 XML 序列化基类
  3. C# 获取枚举 Enum 变量值的 Description 属性
  4. C# 通过文件头判断图像的类型
  5. C# 中反射获取某类的子类和根据类型名动态创建对象