ldap 身份验证的通用步骤

和利用数据库进行验证类似,LDAP中也是利用登陆名和密码进行验证,LDAP中会定义一个属性password,用来存放用户密码,而登陆名使用较多的都是mail地址。那怎么样才能正确的用LDAP进行身份验证呢,下面是一个正确而又通用的步骤:

1. 从客户端得到登陆名和密码。注意这里的登陆名和密码一开始并没有被用到。

2. 先匿名绑定到LDAP服务器,如果LDAP服务器没有启用匿名绑定,一般会提供一个默认的用户,用这个用户进行绑定即可。

3. 之前输入的登陆名在这里就有用了,当上一步绑定成功以后,需要执行一个搜索,而filter就是用登陆名来构造,形如: "(|(uid=$login)(mail=$login))" ,这里的login就是登陆名。搜索执行完毕后,需要对结果进行判断,如果只返回一个entry,这个就是包含了该用户信息的entry,可以得到该entry的DN,后面使用。如果返回不止一个或者没有返回,说明用户名输入有误,应该退出验证并返回错误信息。

4. 如果能进行到这一步,说明用相应的用户,而上一步执行时得到了用户信息所在的entry的DN,这里就需要用这个DN和第一步中得到的password重新绑定LDAP服务器。

5. 执行完上一步,验证的主要过程就结束了,如果能成功绑定,那么就说明验证成功,如果不行,则应该返回密码错误的信息。

这5大步就是基于LDAP的一个 “两次绑定” 验证方法。


[csharp]  view plain  copy
  1. <span style="font-size:18px;">bool checkResult = false;  
  2.                 try  
  3.                 {  
  4.                     string username = Request.Params.Get("username");  
  5.                     string userpwd = Request.Params.Get("userpwd");  
  6.                     string strLADPath = "LDAP://OU=事业部,DC=HOLD,DC=Company,DC=COM";  
  7.                      
  8.                     DirectoryEntry objEntry = new DirectoryEntry(strLADPath);  
  9.                     objEntry.AuthenticationType = AuthenticationTypes.None;  
  10.   
  11.                     DirectorySearcher deSearch = new DirectorySearcher(objEntry);  
  12.                     //过滤名称是否存在  
  13.                     deSearch.Filter = "(&(objectClass=user)(sAMAccountName=" + username + "))";  
  14.                     deSearch.SearchScope = SearchScope.Subtree;  
  15.                     //find the first instance   
  16.                     SearchResult results = deSearch.FindOne();  
  17.                     //check username & userpwd  
  18.                     if (null != results)  
  19.                     {  
  20.                         DirectoryEntry objUserEntry = new DirectoryEntry(results.Path, username, userpwd);  
  21.                         if (null != objUserEntry && null != objUserEntry.Properties  
  22.                             && objUserEntry.Properties.Contains("cn"))  
  23.                         {  
  24.                             checkResult = true;  
  25.                         }  
  26.                     }  
  27.   
  28.                     Response.Write("认证结果:" + checkResult.ToString());  
  29.                 }  
  30.                 catch (System.Exception ex)  
  31.                 {  
  32.                     Response.Write("认证异常"+ex.StackTrace);  
  33.                     Response.Write("认证结果:" + checkResult.ToString());  
  34.                 }</span>  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值