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
- package sunsite.basic;
- import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
- import java.security.MessageDigest;
- import java.security.NoSuchAlgorithmException;
- import java.util.Hashtable;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import javax.naming.Context;
- import javax.naming.NamingException;
- import javax.naming.directory.DirContext;
- import javax.naming.directory.InitialDirContext;
- public class LdapHelper {
- private static DirContext ctx;
- @SuppressWarnings(value = "unchecked")
- public static DirContext getCtx() {
- // if (ctx != null ) {
- // return ctx;
- // }
- String account = "Manager"; //binddn
- String password = "pwd"; //bindpwd
- String root = "dc=scut,dc=edu,dc=cn"; // root
- Hashtable env = new Hashtable();
- env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
- env.put(Context.PROVIDER_URL, "ldap://localhost:389/" + root);
- env.put(Context.SECURITY_AUTHENTICATION, "simple");
- env.put(Context.SECURITY_PRINCIPAL, "cn="+account );
- env.put(Context.SECURITY_CREDENTIALS, password);
- try {
- // 链接ldap
- ctx = new InitialDirContext(env);
- System.out.println("认证成功");
- } catch (javax.naming.AuthenticationException e) {
- System.out.println("认证失败");
- } catch (Exception e) {
- System.out.println("认证出错:");
- e.printStackTrace();
- }
- return ctx;
- }
- public static void closeCtx(){
- try {
- ctx.close();
- } catch (NamingException ex) {
- Logger.getLogger(LdapHelper.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- @SuppressWarnings(value = "unchecked")
- public static boolean verifySHA(String ldappw, String inputpw)
- throws NoSuchAlgorithmException {
- // MessageDigest 提供了消息摘要算法,如 MD5 或 SHA,的功能,这里LDAP使用的是SHA-1
- MessageDigest md = MessageDigest.getInstance("SHA-1");
- // 取出加密字符
- if (ldappw.startsWith("{SSHA}")) {
- ldappw = ldappw.substring(6);
- } else if (ldappw.startsWith("{SHA}")) {
- ldappw = ldappw.substring(5);
- }
- // 解码BASE64
- byte[] ldappwbyte = Base64.decode(ldappw);
- byte[] shacode;
- byte[] salt;
- // 前20位是SHA-1加密段,20位后是最初加密时的随机明文
- if (ldappwbyte.length <= 20) {
- shacode = ldappwbyte;
- salt = new byte[0];
- } else {
- shacode = new byte[20];
- salt = new byte[ldappwbyte.length - 20];
- System.arraycopy(ldappwbyte, 0, shacode, 0, 20);
- System.arraycopy(ldappwbyte, 20, salt, 0, salt.length);
- }
- // 把用户输入的密码添加到摘要计算信息
- md.update(inputpw.getBytes());
- // 把随机明文添加到摘要计算信息
- md.update(salt);
- // 按SSHA把当前用户密码进行计算
- byte[] inputpwbyte = md.digest();
- // 返回校验结果
- return MessageDigest.isEqual(shacode, inputpwbyte);
- }
- public static void main(String[] args) {
- getCtx();
- }
- }
以上这段代码中,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、添加人员的操作:
- public static boolean addUser(String usr, String pwd) {
- boolean success = false;
- DirContext ctx = null;
- try {
- ctx = LdapHelper.getCtx();
- BasicAttributes attrsbu = new BasicAttributes();
- BasicAttribute objclassSet = new BasicAttribute("objectclass");
- objclassSet.add("person");
- objclassSet.add("top");
- objclassSet.add("organizationalPerson");
- objclassSet.add("inetOrgPerson");
- attrsbu.put(objclassSet);
- attrsbu.put("sn", usr);
- attrsbu.put("uid", usr);
- attrsbu.put("userPassword", pwd);
- ctx.createSubcontext("cn=" + usr + ",ou=People", attrsbu);
- ctx.close();
- return true;
- } catch (NamingException ex) {
- try {
- if (ctx != null) {
- ctx.close();
- }
- } catch (NamingException namingException) {
- namingException.printStackTrace();
- }
- Logger.getLogger(LdapHelper.class.getName()).log(Level.SEVERE, null, ex);
- }
- return false;
- }
这一段代码为每个用户分配了一个cn,使用userPassword的属性来存储用户密码,这一属性是经过SSHA散列的。
3、用户认证:
- public static boolean authenticate(String usr, String pwd) {
- boolean success = false;
- DirContext ctx = null;
- try {
- ctx = LdapHelper.getCtx();
- SearchControls constraints = new SearchControls();
- constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
- // constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
- NamingEnumeration en = ctx.search("", "cn=" + usr, constraints); // 查询所有用户
- while (en != null && en.hasMoreElements()) {
- Object obj = en.nextElement();
- if (obj instanceof SearchResult) {
- SearchResult si = (SearchResult) obj;
- System.out.println("name: " + si.getName());
- Attributes attrs = si.getAttributes();
- if (attrs == null) {
- System.out.println("No attributes");
- } else {
- Attribute attr = attrs.get("userPassword");
- Object o = attr.get();
- byte[] s = (byte[]) o;
- String pwd2 = new String(s);
- success = LdapHelper.verifySHA(pwd2, pwd);
- return success;
- }
- } else {
- System.out.println(obj);
- }
- System.out.println();
- }
- ctx.close();
- } catch (NoSuchAlgorithmException ex) {
- try {
- if (ctx != null) {
- ctx.close();
- }
- } catch (NamingException namingException) {
- namingException.printStackTrace();
- }
- Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
- } catch (NamingException ex) {
- try {
- if (ctx != null) {
- ctx.close();
- }
- } catch (NamingException namingException) {
- namingException.printStackTrace();
- }
- Logger.getLogger(LdapHelper.class.getName()).log(Level.SEVERE, null, ex);
- }
- return false;
- }
这一段代码事实上在查询用户的的cn和密码,当然由于密码这个属性需要散列成SSHA,因此调用了LdapHelper中的verifySHA方法。
3、修改密码:
- public static boolean updatePwdLdap(String usr, String pwd) {
- boolean success = false;
- DirContext ctx = null;
- try {
- ctx = LdapHelper.getCtx();
- ModificationItem[] modificationItem = new ModificationItem[1];
- modificationItem[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userPassword", pwd));
- ctx.modifyAttributes("cn=" + usr+",ou=People", modificationItem);
- ctx.close();
- return true;
- } catch (NamingException ex) {
- try {
- if (ctx != null) {
- ctx.close();
- }
- } catch (NamingException namingException) {
- namingException.printStackTrace();
- }
- Logger.getLogger(LdapHelper.class.getName()).log(Level.SEVERE, null, ex);
- }
- return success;
- }
这一方法实质上执行的是一个ldap update的操作,只不过是把密码散列了一下。
4、删除用户,非常简单,只要执行一下
ctx.destroySubcontext("cn=" + account); 即可。
本文介绍了一种使用LDAP进行用户管理的方法,包括用户认证、添加、密码更新及删除等操作,并详细展示了具体的Java代码实现。
254

被折叠的 条评论
为什么被折叠?



