public class LDAPHelper
    {
        private DirectoryEntry _objDirectoryEntry;         /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="LADPath">ldap的地址,例如"LDAP://***.***.48.110:389/dc=***,dc=com"</param>
        /// <param name="authUserName">连接用户名,例如"cn=root,dc=***,dc=com"</param>
        /// <param name="authPWD">连接密码</param>
        public bool OpenConnection(string LADPath, string authUserName, string authPWD)
        {    //创建一个连接 
             _objDirectoryEntry = new DirectoryEntry(LADPath, authUserName, authPWD, AuthenticationTypes.None);              if (null == _objDirectoryEntry)
             {
                 return false;
             }
             else if (_objDirectoryEntry.Properties!=null&&_objDirectoryEntry.Properties.Count > )
             {
                 return true;
             }
             return false;
        }         /// <summary>
        /// 检测一个用户和密码是否正确
        /// </summary>
        /// <param name="strLDAPFilter">(|(uid= {0})(cn={0}))</param>
        /// <param name="TestUserID">testuserid</param>
        /// <param name="TestUserPwd">testuserpassword</param>
        /// <param name="ErrorMessage"></param>
        /// <returns></returns>
        public bool CheckUidAndPwd(string strLDAPFilter, string TestUserID, string TestUserPwd, ref string ErrorMessage)
        {
            bool blRet = false;
            try
            {
                //创建一个检索
                DirectorySearcher deSearch = new DirectorySearcher(_objDirectoryEntry);
                //过滤名称是否存在
                deSearch.Filter =strLDAPFilter;
                deSearch.SearchScope = SearchScope.Subtree;                 //find the first instance 
                SearchResult objSearResult = deSearch.FindOne();                 //如果用户密码为空
                if (string.IsNullOrEmpty(TestUserPwd))
                {
                    if (null != objSearResult && null != objSearResult.Properties && objSearResult.Properties.Count > )
                    {
                        blRet = true;
                    }
                }
                else if (null != objSearResult && !string.IsNullOrEmpty(objSearResult.Path))
                {
                    //获取用户名路径对应的用户uid
                    int pos = objSearResult.Path.LastIndexOf('/');
                    string uid = objSearResult.Path.Remove(, pos + );
                    DirectoryEntry objUserEntry = new DirectoryEntry(objSearResult.Path, uid, TestUserPwd, AuthenticationTypes.None);
                    if (null != objUserEntry && objUserEntry.Properties.Count > )
                    {
                        blRet = true;
                    }
                }
            }
            catch (Exception ex)
            {
                if (null != _objDirectoryEntry)
                {
                    _objDirectoryEntry.Close();
                }
                ErrorMessage = "检测异常:"+ex.StackTrace;
            }
            return blRet;
        }         /// <summary>
        /// 关闭连接
        /// </summary>
        public void closeConnection()
        {
            if (null != _objDirectoryEntry)
            {
                _objDirectoryEntry.Close();
            }
        }
    }

写了一个通用的认证类,请看代码

private void btnCheck_Click(object sender, EventArgs e)
{ string strLDAPFilter = string.Format(txtFilter.Text, txtUserName.Text.Trim());
//deSearch.Filter = "(&(objectClass=user)(sAMAccountName=" + username + "))"; string TestUserID = txtUserName.Text;
string TestUserPwd = txtPwd.Text;
LDAPHelper objldap = new LDAPHelper();
string strLDAPPath = txtLDAP.Text;
string strLDAPAdminName = txtLUserName.Text;
string strLDAPAdminPwd = txtLPwd.Text;
string strMsg = "";
bool blRet = objldap.OpenConnection(strLDAPPath, strLDAPAdminName, strLDAPAdminPwd); if (blRet)
{
blRet = objldap.CheckUidAndPwd(strLDAPFilter, TestUserID, TestUserPwd, ref strMsg);
if (blRet)
{
strMsg = "检测用户名" + TestUserID + "和密码" + TestUserPwd + "成功";
}
else if (!blRet && string.IsNullOrEmpty(strMsg))
{
strMsg = "检测用户名" + TestUserID + "和密码" + TestUserPwd + "失败";
}
}
this.txtLog.Text = System.DateTime.Now.ToString() + ":" + strMsg + "\r\n" + "\r\n" + this.txtLog.Text;
MessageBox.Show(strMsg);
}
}
public class LDAPHelper
{
private DirectoryEntry _objDirectoryEntry; /// <summary>
/// 构造函数
/// </summary>
/// <param name="LADPath">ldap的地址,例如"LDAP://***.***.48.110:389/dc=***,dc=com"</param>
/// <param name="authUserName">连接用户名,例如"cn=root,dc=***,dc=com"</param>
/// <param name="authPWD">连接密码</param>
public bool OpenConnection(string LADPath, string authUserName, string authPWD)
{ //创建一个连接
_objDirectoryEntry = new DirectoryEntry(LADPath, authUserName, authPWD, AuthenticationTypes.None); if (null == _objDirectoryEntry)
{
return false;
}
else if (_objDirectoryEntry.Properties!=null&&_objDirectoryEntry.Properties.Count > )
{
return true;
}
return false;
} /// <summary>
/// 检测一个用户和密码是否正确
/// </summary>
/// <param name="strLDAPFilter">(|(uid= {0})(cn={0}))</param>
/// <param name="TestUserID">testuserid</param>
/// <param name="TestUserPwd">testuserpassword</param>
/// <param name="ErrorMessage"></param>
/// <returns></returns>
public bool CheckUidAndPwd(string strLDAPFilter, string TestUserID, string TestUserPwd, ref string ErrorMessage)
{
bool blRet = false;
try
{
//创建一个检索
DirectorySearcher deSearch = new DirectorySearcher(_objDirectoryEntry);
//过滤名称是否存在
deSearch.Filter =strLDAPFilter;
deSearch.SearchScope = SearchScope.Subtree; //find the first instance
SearchResult objSearResult = deSearch.FindOne(); //如果用户密码为空
if (string.IsNullOrEmpty(TestUserPwd))
{
if (null != objSearResult && null != objSearResult.Properties && objSearResult.Properties.Count > )
{
blRet = true;
}
}
else if (null != objSearResult && !string.IsNullOrEmpty(objSearResult.Path))
{
//获取用户名路径对应的用户uid
int pos = objSearResult.Path.LastIndexOf('/');
string uid = objSearResult.Path.Remove(, pos + );
DirectoryEntry objUserEntry = new DirectoryEntry(objSearResult.Path, uid, TestUserPwd, AuthenticationTypes.None);
if (null != objUserEntry && objUserEntry.Properties.Count > )
{
blRet = true;
}
}
}
catch (Exception ex)
{
if (null != _objDirectoryEntry)
{
_objDirectoryEntry.Close();
}
ErrorMessage = "检测异常:"+ex.StackTrace;
}
return blRet;
} /// <summary>
/// 关闭连接
/// </summary>
public void closeConnection()
{
if (null != _objDirectoryEntry)
{
_objDirectoryEntry.Close();
}
}
}

调用

private void btnCheck_Click(object sender, EventArgs e)
{ string strLDAPFilter = string.Format(txtFilter.Text, txtUserName.Text.Trim());
//deSearch.Filter = "(&(objectClass=user)(sAMAccountName=" + username + "))"; string TestUserID = txtUserName.Text;
string TestUserPwd = txtPwd.Text;
LDAPHelper objldap = new LDAPHelper();
string strLDAPPath = txtLDAP.Text;
string strLDAPAdminName = txtLUserName.Text;
string strLDAPAdminPwd = txtLPwd.Text;
string strMsg = "";
bool blRet = objldap.OpenConnection(strLDAPPath, strLDAPAdminName, strLDAPAdminPwd); if (blRet)
{
blRet = objldap.CheckUidAndPwd(strLDAPFilter, TestUserID, TestUserPwd, ref strMsg);
if (blRet)
{
strMsg = "检测用户名" + TestUserID + "和密码" + TestUserPwd + "成功";
}
else if (!blRet && string.IsNullOrEmpty(strMsg))
{
strMsg = "检测用户名" + TestUserID + "和密码" + TestUserPwd + "失败";
}
}
this.txtLog.Text = System.DateTime.Now.ToString() + ":" + strMsg + "\r\n" + "\r\n" + this.txtLog.Text;
MessageBox.Show(strMsg);
}
}

实例下载:http://download.csdn.net/detail/paolei/6740833

LDAP是轻量目录访问协议,英文全称是Lightweight Directory Access Protocol,一般都简称为LDAP。它是基于X.500标准的,但是简单多了并且可以根据需要定制。与X.500不同,LDAP支持TCP/IP,这对访问Internet是必须的。LDAP的核心规范在RFC中都有定义,所有与LDAP相关的RFC都可以在LDAPman RFC网页中找到。

bool checkResult = false;
try
{
string username = Request.Params.Get("username");
string userpwd = Request.Params.Get("userpwd");
string strLADPath = "LDAP://OU=事业部,DC=HOLD,DC=Company,DC=COM"; DirectoryEntry objEntry = new DirectoryEntry(strLADPath);
objEntry.AuthenticationType = AuthenticationTypes.None; DirectorySearcher deSearch = new DirectorySearcher(objEntry);
//过滤名称是否存在
deSearch.Filter = "(&(objectClass=user)(sAMAccountName=" + username + "))";
deSearch.SearchScope = SearchScope.Subtree;
//find the first instance
SearchResult results = deSearch.FindOne();
//check username & userpwd
if (null != results)
{
DirectoryEntry objUserEntry = new DirectoryEntry(results.Path, username, userpwd);
if (null != objUserEntry && null != objUserEntry.Properties
&& objUserEntry.Properties.Contains("cn"))
{
checkResult = true;
}
} Response.Write("认证结果:" + checkResult.ToString());
}
catch (System.Exception ex)
{
Response.Write("认证异常"+ex.StackTrace);
Response.Write("认证结果:" + checkResult.ToString());
} private void btnCheck_Click(object sender, EventArgs e)
{ string strLDAPFilter = string.Format(txtFilter.Text, txtUserName.Text.Trim());
//deSearch.Filter = "(&(objectClass=user)(sAMAccountName=" + username + "))"; string TestUserID = txtUserName.Text;
string TestUserPwd = txtPwd.Text;
LDAPHelper objldap = new LDAPHelper();
string strLDAPPath = txtLDAP.Text;
string strLDAPAdminName = txtLUserName.Text;
string strLDAPAdminPwd = txtLPwd.Text;
string strMsg = "";
bool blRet = objldap.OpenConnection(strLDAPPath, strLDAPAdminName, strLDAPAdminPwd); if (blRet)
{
blRet = objldap.CheckUidAndPwd(strLDAPFilter, TestUserID, TestUserPwd, ref strMsg);
if (blRet)
{
strMsg = "检测用户名" + TestUserID + "和密码" + TestUserPwd + "成功";
}
else if (!blRet && string.IsNullOrEmpty(strMsg))
{
strMsg = "检测用户名" + TestUserID + "和密码" + TestUserPwd + "失败";
}
}
this.txtLog.Text = System.DateTime.Now.ToString() + ":" + strMsg + "\r\n" + "\r\n" + this.txtLog.Text;
MessageBox.Show(strMsg);
}
} public class LDAPHelper
{
private DirectoryEntry _objDirectoryEntry; /// <summary>
/// 构造函数
/// </summary>
/// <param name="LADPath">ldap的地址,例如"LDAP://***.***.48.110:389/dc=***,dc=com"</param>
/// <param name="authUserName">连接用户名,例如"cn=root,dc=***,dc=com"</param>
/// <param name="authPWD">连接密码</param>
public bool OpenConnection(string LADPath, string authUserName, string authPWD)
{ //创建一个连接
_objDirectoryEntry = new DirectoryEntry(LADPath, authUserName, authPWD, AuthenticationTypes.None); if (null == _objDirectoryEntry)
{
return false;
}
else if (_objDirectoryEntry.Properties!=null&&_objDirectoryEntry.Properties.Count > )
{
return true;
}
return false;
} /// <summary>
/// 检测一个用户和密码是否正确
/// </summary>
/// <param name="strLDAPFilter">(|(uid= {0})(cn={0}))</param>
/// <param name="TestUserID">testuserid</param>
/// <param name="TestUserPwd">testuserpassword</param>
/// <param name="ErrorMessage"></param>
/// <returns></returns>
public bool CheckUidAndPwd(string strLDAPFilter, string TestUserID, string TestUserPwd, ref string ErrorMessage)
{
bool blRet = false;
try
{
//创建一个检索
DirectorySearcher deSearch = new DirectorySearcher(_objDirectoryEntry);
//过滤名称是否存在
deSearch.Filter =strLDAPFilter;
deSearch.SearchScope = SearchScope.Subtree; //find the first instance
SearchResult objSearResult = deSearch.FindOne(); //如果用户密码为空
if (string.IsNullOrEmpty(TestUserPwd))
{
if (null != objSearResult && null != objSearResult.Properties && objSearResult.Properties.Count > )
{
blRet = true;
}
}
else if (null != objSearResult && !string.IsNullOrEmpty(objSearResult.Path))
{
//获取用户名路径对应的用户uid
int pos = objSearResult.Path.LastIndexOf('/');
string uid = objSearResult.Path.Remove(, pos + );
DirectoryEntry objUserEntry = new DirectoryEntry(objSearResult.Path, uid, TestUserPwd, AuthenticationTypes.None);
if (null != objUserEntry && objUserEntry.Properties.Count > )
{
blRet = true;
}
}
}
catch (Exception ex)
{
if (null != _objDirectoryEntry)
{
_objDirectoryEntry.Close();
}
ErrorMessage = "检测异常:"+ex.StackTrace;
}
return blRet;
} /// <summary>
/// 关闭连接
/// </summary>
public void closeConnection()
{
if (null != _objDirectoryEntry)
{
_objDirectoryEntry.Close();
}
}
}

C# LDAP认证登录类参考的更多相关文章

  1. C# LDAP认证登录

    LDAP是轻量目录访问协议,英文全称是Lightweight Directory Access Protocol,一般都简称为LDAP.它是基于X.500标准的,但是简单多了并且可以根据需要定制.与X ...

  2. Shrio00 Shiro认证登录、权限管理环境搭建

    基础环境准备: JDK -> java version "1.8.0_101" MAVEN -> Apache Maven 3.5.0 1 导入依赖 mysql驱动 m ...

  3. 基于Thinkphp3.2的qq第三方oauth认证登录扩展类

    基于Thinkphp3.2的qq第三方oauth认证登录扩展类,由于腾讯oauth sdk写的太多,不能与thinkphp和好的结合,最终想法讲腾讯oauth sdk写成tp的扩展类先看代码,将代码保 ...

  4. No.2 CAS之SPNEGO+LDAP认证配置

    1.概述 本文先配置了SPNEGO认证,就是如果用户操作系统如果登陆了公司的Windows域,用户浏览器访问应用服务即可免登录. 然后如果不在域里的员工,用LDAP认证方式,输账号密码登陆. 参考文档 ...

  5. C#开发中Windows域认证登录2(扩展吉日嘎拉GPM系统)

    原文地址:http://www.cuiwenyuan.com/shanghai/post/Windows-AD-Logon-Intergrated-into-Jirigala-GPM-DotNet-B ...

  6. centos 6.4配置samba+ldap认证

    原文地址:http://www.centoscn.com/image-text/config/2015/0716/5866.html  1. 什么是samba Samba服务类似于windows上的共 ...

  7. 搭建harbor仓库、LDAP认证

    ldap: 192.168.199.177 c5game.com 宿主机:192.168.199.224 测试客户机:192.168.199.223 安装docker.docker-compose 访 ...

  8. C#开发中Windows域认证登录2016(扩展吉日嘎拉GPM系统V4.2)

    2013年搞公司的OA时,为了统一用户登录,将Windows AD的用户和OA的账号对接,OA用户名的规则就是使用Windows AD的用户名,格式举例:Troy.Cui,原理就是先进行域服务器的认证 ...

  9. 拦截器的作用之session认证登录和资源拦截

    背景: 在项目中我使用了自定义的Filter 这时候过滤了很多路径,当然对静态资源我是直接放过去的,但是,还是出现了静态资源没办法访问到springboot默认的文件夹中得文件.另外,经常需要判断当前 ...

随机推荐

  1. 澄清Fundebug录屏技术的几点误会

    1. "视频"并非真的视频.也不是通过连续播放大量截图来实现 首先请大家观看这个视频: 视频中,当鼠标点击"场景重现",会立即播放一段"视频" ...

  2. 用Random产生1到10之间的一个随机数

    bat中怎样用Random产生1到10之间的一个随机数? 当然是用%random%,示例: @echo off rem 用Random产生1到10之间的一个随机数 set num=%random% s ...

  3. 服务器CPU很高,频繁FullGC排查小总结

    可以分为如下步骤: ①通过 top 命令查看 CPU 情况,如果 CPU 比较高,则通过 top -Hp 命令查看当前进程的各个线程运行情况. 找出 CPU 过高的线程之后,将其线程 id 转换为十六 ...

  4. odoo10学习笔记四:onchange、唯一性约束

    转载请注明原文地址:https://www.cnblogs.com/ygj0930/p/11189273.html 一:onchange机制[onchange=前端js函数!可以实现前端实时更新以及修 ...

  5. adb命令之解锁打卡

    adb devicesadb shell input keyevent 26                       按手机电源键adb shell input swipe 400 1080 40 ...

  6. loadrunner12 Runtime Settings位置

  7. Dockerfile解析(八)

    一.Dockerfile是什么 Dockerfile是用来构建Docker镜像的构建文件,是由一系列命令和参数构成的脚本. 1. 构建的步骤 运行容器:docker run 构建新的镜像:docker ...

  8. 洛谷 P2357 守墓人

    洛谷 P2357 守墓人 题目描述 在一个荒凉的墓地上 有一个令人尊敬的守墓人, 他看守的墓地从来 没有被盗过, 所以人们很放心的把自己的先人的墓 安顿在他那 守墓人能看好这片墓地是必然而不是偶然.. ...

  9. UVA10559 方块消除 Blocks 题解

    设g[i][j][k]为消去区间[i,j]中的方块,只留下k个与a[i]颜色相同的方块的最大价值,f[i][j]为将[i,j]中所有方块消去的价值,转移自己yy一下即可. 为什么这样是对的?因为对于一 ...

  10. 洛谷4965 薇尔莉特的打字机(Trie,DP)

    神仙题. 考虑在一棵 Trie 上进行染色,将可能出现的串的末尾染成黑色.答案就是黑点的个数.一开始只有 \(A\) 的末尾点是黑色. 当出现一个字符(不是退格)\(c\) 时,就要将每个黑点的 \( ...