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. [b0016] python 归纳 (二)_静态方法和类方法

    # -*- coding: UTF-8 -*- """ 测试 类的静态方法,类方法 @staticmethod @classmethod 总结: 1. self 指向类对 ...

  2. Spring Cloud Bus介绍--Spring Cloud学习第七天(非原创)

    一.什么是Spring Cloud Bus二.Spring Cloud Bus之RabbitMQ介绍三.Spring Cloud Bus整合RabbitMQ四.Spring Cloud Bus整合Ka ...

  3. 笔记13:Python 和 Elasticsearch 构建简易搜索

    Python 和 Elasticsearch 构建简易搜索 1 ES基本介绍 概念介绍 Elasticsearch是一个基于Lucene库的搜索引擎.它提供了一个分布式.支持多租户的全文搜索引擎,它可 ...

  4. 09事件传递参数-封装网络请求api get和post合并整合在一起

    1==>通过点击事件进行传递参数 <view bindtap="goEdution" data-index="5">西南大学</view ...

  5. Linux(CentOS)上,安装了Apache(httpd)后,其他的电脑无法访问的原因

    今天试了下在虚拟机上利用CentOS系统的yum命令安装好了httpd(apache2.2),然后在windows系统下访问此虚拟机的ip地址,却访问不了. 因为前段时间有知道过iptable的限制, ...

  6. SQL必知必会02 过滤数据/条件查询

  7. linux的cpu使用率

    linux 上一个核占满是 100%,双核机器占满整个 CPU 是 200%

  8. 学习:逆向PUSH越界/INT 68/反调试导致的程序

    自己根据shark恒老师的分析,总结一下: 一般反调试自动关闭程序利用的函数有: 1.CreateToolhelp32Snapshot 2.FindWindow 3.ExitProcess 4.Pos ...

  9. 【JSP】${pageContext.request.contextPath}

    取出部署的应用程序名或者是当前的项目名称 http://localhost:8080/demo1/a.jsp  ${pageContext.request.contextPath}或<%=req ...

  10. java基础JDK jvm path环境变量

    JDk=JRE +java的开发工具(javac.exe java.exe javadoc.exe)JRE =JVM +Java核心类库 2.为什么 要配置 path环境变量 ?如何配置?JAVA_H ...