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. 微信支付:chooseWXPay:fail, the permission value is offline verifying

    在开发公众号微信支付的时候,到了支付那一步,页面上看到微信支付的loading一闪而过,但是没有出现微信支付的页面.控制台log显示错误信息:“chooseWXPay:fail, the permis ...

  2. 无法解析的外部符号 "void __cdecl cv::imshow

    解决方法: 把编译环境放到其他没有报错的项目上,编译通过.

  3. 解决IIS7、IIS7.5 应用程序池回收假死的方法

    最近iis网站一直假死状态,都懵了,查看程序有没有关闭数据库,反复捣鼓,还一直测试是否是程序应用池自动回收问题依然没有效果.经过老师提醒,找到了解决办法,在此做个笔记! 原因在于:应用程序池超时配置被 ...

  4. day39_8_23mysql的其他内容(视图等)

    一.视图 MySQL中有一种比较方便的表,就是视图(view). 什么是视图? 视图就是通过查询获得一张虚拟表,然后将其保存,下次可以直接使用这个视图. 使用视图就可以不需要重复查询/连接表,在代码层 ...

  5. 【大数据】0001---使用SparkSQL关联两个表求和取前几行

    场景: 有两个表,表可以是文本或Json数据,结构化后分别是Table1(A,B,C)和Table2(C.D.E),两个表通过C关联,要求求出D+E之和,并以(A.B.D+E)三列返回 解答: 思路: ...

  6. (day48作业)jQuery+Bootstrap练习题

    目录 一.图书管理系统页面搭建 二.jQuery练习题 一.图书管理系统页面搭建 <!DOCTYPE html> <html lang="en"> < ...

  7. 2.第一个Vue程序

    1.IDEA中安装Vue.js插件 2.建立项目以及html文件 1.创建一个 HTML 文件 2.引入 Vue.js <script src="https://cdn.jsdeliv ...

  8. selenium--cookie操作

    前戏 在做自动化的时候,遇到难处理的验证码,我们可以手动登录,然后获取登录到的cookie,添加到浏览器中,就可以实现登录 实战 from selenium import webdriver driv ...

  9. 数据结构or算法

    其实长久以来 mrxfyxj一直纠结着数据结构和算法到底有什么区别 只要学了一个算法就在惋惜她为什么不能是数据结构 产生这种想法的原因是mrxf觉得他blog里数据结构的东西很少 而mrxf自身又有一 ...

  10. [LeetCode] 75. Sort Colors 颜色排序

    Given an array with n objects colored red, white or blue, sort them in-place so that objects of the ...