JAVA中使用LDAP进行用户认证

LDAP的英文全称是Lightweight Directory Access Protocol,一般都简称为LDAP。它是基于X.500标准的,但是简单多了并且可以根据需要定制。与X.500不同,LDAP支持TCP/IP,这对访问Internet是必须的。LDAP的核心规范在RFC中都有定义,所有与LDAP相关的RFC都可以在LDAPman RFC网页中找到。现在LDAP技术不仅发展得很快而且也是激动人心的。在企业范围内实现LDAP可以让运行在几乎所有计算机平台上的所有的应用程序从 LDAP目录中获取信息。LDAP目录中可以存储各种类型的数据:电子邮件地址、邮件路由信息、人力资源数据、公用密匙、联系人列表,等等。通过把 LDAP目录作为系统集成中的一个重要环节,可以简化员工在企业内部查询信息的步骤,甚至连主要的数据源都可以放在任何地方。
        在前一阵子改版Sun SITE的时候,由于考虑到学校里的同学们使用的基本都是教育网,连接外网很麻烦,所以学习learningconnection上的课程也非常的麻烦,于是我和Vincent就考虑把SAI的一部分课程移植到Sun SITE上面来,以供教育网的同学使用。我们使用了Sakai这一套开源软件来提供SAI课程的在线学习,由于Sakai的用户需要在LDAP上进行认证,因此需要把用户认证放到LDAP上来。在学习使用LDAP的过程中遇到了一些问题,现在总结一下:
1、管理连接的LdapHelper.Java

[java]  view plain  copy
  1. package sunsite.basic;  
  2.   
  3. import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;  
  4. import java.security.MessageDigest;  
  5. import java.security.NoSuchAlgorithmException;  
  6. import java.util.Hashtable;  
  7. import java.util.logging.Level;  
  8. import java.util.logging.Logger;  
  9. import javax.naming.Context;  
  10. import javax.naming.NamingException;  
  11. import javax.naming.directory.DirContext;  
  12. import javax.naming.directory.InitialDirContext;  
  13.   
  14.   
  15. public class LdapHelper {  
  16.   
  17.     private static DirContext ctx;  
  18.   
  19.     @SuppressWarnings(value = "unchecked")  
  20.     public static DirContext getCtx() {  
  21. //        if (ctx != null ) {  
  22. //            return ctx;  
  23. //        }  
  24.         String account = "Manager"//binddn   
  25.         String password = "pwd";    //bindpwd  
  26.         String root = "dc=scut,dc=edu,dc=cn"// root  
  27.         Hashtable env = new Hashtable();  
  28.         env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");  
  29.         env.put(Context.PROVIDER_URL, "ldap://localhost:389/" + root);  
  30.         env.put(Context.SECURITY_AUTHENTICATION, "simple");  
  31.         env.put(Context.SECURITY_PRINCIPAL, "cn="+account );  
  32.         env.put(Context.SECURITY_CREDENTIALS, password);  
  33.         try {  
  34.             // 链接ldap  
  35.             ctx = new InitialDirContext(env);  
  36.             System.out.println("认证成功");  
  37.         } catch (javax.naming.AuthenticationException e) {  
  38.             System.out.println("认证失败");  
  39.         } catch (Exception e) {  
  40.             System.out.println("认证出错:");  
  41.             e.printStackTrace();  
  42.         }  
  43.         return ctx;  
  44.     }  
  45.       
  46.     public static void closeCtx(){  
  47.         try {  
  48.             ctx.close();  
  49.         } catch (NamingException ex) {  
  50.             Logger.getLogger(LdapHelper.class.getName()).log(Level.SEVERE, null, ex);  
  51.         }  
  52.     }  
  53.       
  54.     @SuppressWarnings(value = "unchecked")  
  55.     public static boolean verifySHA(String ldappw, String inputpw)  
  56.             throws NoSuchAlgorithmException {  
  57.   
  58.         // MessageDigest 提供了消息摘要算法,如 MD5 或 SHA,的功能,这里LDAP使用的是SHA-1  
  59.         MessageDigest md = MessageDigest.getInstance("SHA-1");  
  60.   
  61.         // 取出加密字符  
  62.         if (ldappw.startsWith("{SSHA}")) {  
  63.             ldappw = ldappw.substring(6);  
  64.         } else if (ldappw.startsWith("{SHA}")) {  
  65.             ldappw = ldappw.substring(5);  
  66.         }  
  67.   
  68.         // 解码BASE64  
  69.         byte[] ldappwbyte = Base64.decode(ldappw);  
  70.         byte[] shacode;  
  71.         byte[] salt;  
  72.   
  73.         // 前20位是SHA-1加密段,20位后是最初加密时的随机明文  
  74.         if (ldappwbyte.length <= 20) {  
  75.             shacode = ldappwbyte;  
  76.             salt = new byte[0];  
  77.         } else {  
  78.             shacode = new byte[20];  
  79.             salt = new byte[ldappwbyte.length - 20];  
  80.             System.arraycopy(ldappwbyte, 0, shacode, 020);  
  81.             System.arraycopy(ldappwbyte, 20, salt, 0, salt.length);  
  82.         }  
  83.   
  84.         // 把用户输入的密码添加到摘要计算信息  
  85.         md.update(inputpw.getBytes());  
  86.         // 把随机明文添加到摘要计算信息  
  87.         md.update(salt);  
  88.   
  89.         // 按SSHA把当前用户密码进行计算  
  90.         byte[] inputpwbyte = md.digest();  
  91.   
  92.         // 返回校验结果  
  93.         return MessageDigest.isEqual(shacode, inputpwbyte);  
  94.     }  
  95.   
  96.     public static void main(String[] args) {  
  97.         getCtx();  
  98.     }  
  99.     
  100. }  


以上这段代码中,public static DirContext getCtx() 这一个方法负责建立与ldap服务器的连接,public static boolean verifySHA(String ldappw, String inputpw)
方法负责判断将明文密码跟ldap中的用户密码进行匹配判断。因为ldap中的用户密码是经过SSHA散列的,因此必须将明文转换为SSHA码才能够进行匹配。这一个算法,我是参考http://raistlin.spaces.live.com/blog/cns!20be4528d42aa141!165.entry上的代码,仅作为学习参考而用。

2、添加人员的操作:

[java]  view plain  copy
  1. public static boolean addUser(String usr, String pwd) {  
  2.         boolean success = false;  
  3.         DirContext ctx = null;  
  4.         try {  
  5.             ctx = LdapHelper.getCtx();  
  6.             BasicAttributes attrsbu = new BasicAttributes();  
  7.             BasicAttribute objclassSet = new BasicAttribute("objectclass");  
  8.             objclassSet.add("person");  
  9.             objclassSet.add("top");  
  10.             objclassSet.add("organizationalPerson");  
  11.             objclassSet.add("inetOrgPerson");  
  12.             attrsbu.put(objclassSet);  
  13.             attrsbu.put("sn", usr);  
  14.             attrsbu.put("uid", usr);  
  15.             attrsbu.put("userPassword", pwd);  
  16.             ctx.createSubcontext("cn=" + usr + ",ou=People", attrsbu);  
  17.             ctx.close();  
  18.             return true;  
  19.         } catch (NamingException ex) {  
  20.             try {  
  21.                 if (ctx != null) {  
  22.                     ctx.close();  
  23.                 }  
  24.             } catch (NamingException namingException) {  
  25.                 namingException.printStackTrace();  
  26.             }  
  27.             Logger.getLogger(LdapHelper.class.getName()).log(Level.SEVERE, null, ex);  
  28.         }  
  29.         return false;  
  30.     }  

这一段代码为每个用户分配了一个cn,使用userPassword的属性来存储用户密码,这一属性是经过SSHA散列的。
3、用户认证:

[java]  view plain  copy
  1. public static boolean authenticate(String usr, String pwd) {  
  2.         boolean success = false;  
  3.         DirContext ctx = null;  
  4.         try {  
  5.             ctx = LdapHelper.getCtx();  
  6.             SearchControls constraints = new SearchControls();  
  7.             constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);  
  8.             // constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);  
  9.             NamingEnumeration en = ctx.search("""cn=" + usr, constraints); // 查询所有用户  
  10.             while (en != null && en.hasMoreElements()) {  
  11.                 Object obj = en.nextElement();  
  12.                 if (obj instanceof SearchResult) {  
  13.                     SearchResult si = (SearchResult) obj;  
  14.                     System.out.println("name:   " + si.getName());  
  15.                     Attributes attrs = si.getAttributes();  
  16.                     if (attrs == null) {  
  17.                         System.out.println("No   attributes");  
  18.                     } else {  
  19.                         Attribute attr = attrs.get("userPassword");  
  20.                         Object o = attr.get();  
  21.                         byte[] s = (byte[]) o;  
  22.                         String pwd2 = new String(s);  
  23.                         success = LdapHelper.verifySHA(pwd2, pwd);  
  24.                         return success;  
  25.                     }  
  26.                 } else {  
  27.                     System.out.println(obj);  
  28.                 }  
  29.                 System.out.println();  
  30.             }  
  31.             ctx.close();  
  32.         } catch (NoSuchAlgorithmException ex) {  
  33.             try {  
  34.                 if (ctx != null) {  
  35.                     ctx.close();  
  36.                 }  
  37.             } catch (NamingException namingException) {  
  38.                 namingException.printStackTrace();  
  39.             }  
  40.             Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);  
  41.         } catch (NamingException ex) {  
  42.             try {  
  43.                 if (ctx != null) {  
  44.                     ctx.close();  
  45.                 }  
  46.             } catch (NamingException namingException) {  
  47.                 namingException.printStackTrace();  
  48.             }  
  49.             Logger.getLogger(LdapHelper.class.getName()).log(Level.SEVERE, null, ex);  
  50.         }  
  51.         return false;  
  52.     }  

这一段代码事实上在查询用户的的cn和密码,当然由于密码这个属性需要散列成SSHA,因此调用了LdapHelper中的verifySHA方法。
3、修改密码:

[java]  view plain  copy
  1. public static boolean updatePwdLdap(String usr, String pwd) {  
  2.         boolean success = false;  
  3.         DirContext ctx = null;  
  4.         try {  
  5.             ctx = LdapHelper.getCtx();  
  6.             ModificationItem[] modificationItem = new ModificationItem[1];  
  7.             modificationItem[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userPassword", pwd));  
  8.             ctx.modifyAttributes("cn=" + usr+",ou=People", modificationItem);  
  9.             ctx.close();  
  10.             return true;  
  11.         } catch (NamingException ex) {  
  12.             try {  
  13.                 if (ctx != null) {  
  14.                     ctx.close();  
  15.                 }  
  16.             } catch (NamingException namingException) {  
  17.                 namingException.printStackTrace();  
  18.             }  
  19.             Logger.getLogger(LdapHelper.class.getName()).log(Level.SEVERE, null, ex);  
  20.         }  
  21.         return success;  
  22.     }  

这一方法实质上执行的是一个ldap update的操作,只不过是把密码散列了一下。
4、删除用户,非常简单,只要执行一下
ctx.destroySubcontext("cn=" + account);   即可。

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值