标签:
1.核心连接代码
package com.test.ldap; import java.util.Hashtable; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.BasicAttribute; import javax.naming.directory.DirContext; import javax.naming.directory.ModificationItem; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import javax.naming.ldap.Control; import javax.naming.ldap.InitialLdapContext; import javax.naming.ldap.LdapContext; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.test.Constants; import com.test.util.SHA1; /** * LDAP登陆工具类 */ public class LDAPAuthentication { private final String BASEDN = Constants.ldapBasedn; private final String FACTORY = "com.sun.jndi.ldap.LdapCtxFactory"; private LdapContext ctx = null; private final Control[] connCtls = null; private Log log = null; private void LDAP_connect() throws Exception { Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, FACTORY); env.put(Context.PROVIDER_URL, Constants.ldapURL); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, Constants.ldapPrincipal); env.put(Context.SECURITY_CREDENTIALS, Constants.ldapCredentials); try { ctx = new InitialLdapContext(env, connCtls); log.info("认证LDAP服务器(" + Constants.ldapURL + ")成功!"); } catch (javax.naming.AuthenticationException e) { log.error("认证LDAP服务器(" + Constants.ldapURL + ")失败!"); log.error("原因:" + e); throw new Exception(); } catch (Exception e) { log.error("认证LDAP服务器(" + Constants.ldapURL + ")失败!"); log.error("原因:" + e); throw new Exception(); } } private void closeLdapContext() { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { e.printStackTrace(); } } } private String getUserDN(String uid) { try { String userDN = ""; SearchControls constraints = new SearchControls(); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); // 查找用户DN NamingEnumeration<SearchResult> en = ctx.search(BASEDN, Constants.ldapFilter.replace("#arg", uid), constraints); // 此注释上下不要打印en.hasMoreElements()代码,此调用存在BUG,当返回false时内部会自动变成true while (en != null && en.hasMoreElements()) { Object obj = en.nextElement(); if (obj instanceof SearchResult) { SearchResult si = (SearchResult) obj; userDN += si.getName(); userDN += "," + BASEDN; System.out.println(userDN); log.info("查找到用户" + uid + "的DN信息:" + userDN); } else { } } return userDN; } catch (NamingException e) { log.error("查找用户DN时错误!"); log.error("原因:" + e); return null; } catch (Exception e1) { return null; } } /** * 登陆AD平台验证客户 * * @param UID * 用户名 * @param password * 密码 * @param log * 日志对象 * @return */ public boolean authenricate(String UID, String password, Log log) { //是否成功 boolean valide = false; if (log != null) { this.log = log; } else { this.log = (this.log != null ? this.log : LogFactory.getLog(getClass())); } // 因java naming调用LDAP空密码时会导致跳过验证直接成功,所以要求非空验证 if (StringUtils.isBlank(password)) { this.log.info("密码不可为空!"); return false; } try { //连接 LDAP_connect(); String userDN = getUserDN(UID); if (StringUtils.isNotBlank(userDN)) { // 如果需要加密SHA-1 // password = SHA1.shaBase64(password); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password); ctx.reconnect(connCtls); System.out.println(userDN + " 验证通过"); this.log.info("LDAP用户验证成功!"); valide = true; } else { this.log.info("未找到" + UID + "用户信息!"); valide = false; } } catch (NamingException e) { this.log.info("用户信息认证失败!password:" + password); valide = false; } catch (Exception e) { //创建连接失败 valide = false; } finally { // 关闭连接 closeLdapContext(); } return valide; } /** * 修改密码 * * @param UID * @param pwd * @return */ public boolean updatePwdLdap(String UID, String pwd) { boolean success = false; try { LDAP_connect(); ModificationItem[] modificationItem = new ModificationItem[1]; modificationItem[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userPassword", SHA1.shaBase64(pwd))); String userDN = getUserDN(UID); ctx.modifyAttributes(userDN, modificationItem); return true; } catch (NamingException ex) { ex.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { // 关闭连接 closeLdapContext(); } return success; } public static void main(String[] args) { LDAPAuthentication ldap = new LDAPAuthentication(); if (ldap.authenricate("aa", "bb", null) == true) { System.out.println("该用户认证成功"); } } }
2.各参数描述
public class Constants { /** * LDAP服务端地址URL(端口默认389) */ public static final String ldapURL= "ldap://10.1.205.56:389/"; /** * LDAP根 */ public static final String ldapBasedn= "DC=GPTest,DC=com"; /** * LDAP登陆账号(注:特殊字符\需要进行转义) */ public static final String ldapPrincipal= "LADPTest"; /** * LDAP登陆密码 */ public static final String ldapCredentials= "abcdef"; /** * <B>LDAP查询Filter <br/>#arg在代码中可替换为实际查找用户的用户账号<b/> */ public static final String ldapFilter= "(&(objectClass=user)(sAMAccountName=#arg))"; }
3.如果查询用户时需要对密码进行SHA-1加密,则使用下面的类
package com.test.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.apache.commons.codec.binary.Base64; /** * SHA-1加密 */ public class SHA1 { public static String Encrypt(String strSrc) { MessageDigest md = null; String strDes = null; byte[] bt = strSrc.getBytes(); try { md = MessageDigest.getInstance("SHA-1"); md.update(bt); strDes = bytes2Hex(md.digest()); // to HexString } catch (NoSuchAlgorithmException e) { System.out.println("Invalid algorithm."); return null; } return strDes; } private static String bytes2Hex(byte[] bts) { String des = ""; String tmp = null; for (int i = 0; i < bts.length; i++) { tmp = (Integer.toHexString(bts[i] & 0xFF)); if (tmp.length() == 1) { des += "0"; } des += tmp; } return des; } @SuppressWarnings("static-access") public static void main(String[] args) { SHA1 te = new SHA1(); String strSrc = "123456"; System.out.println("Use SHA:" + te.Encrypt(strSrc)); System.out.println("Use a :"+te.shaBase64("123456")); } public static String shaBase64(String str) { String rawPass = str; MessageDigest sha; String pswSHA = null; try { sha = MessageDigest.getInstance("SHA-1"); sha.update(rawPass.getBytes()); byte[] hash = sha.digest(); pswSHA = "{SHA}" + new String(Base64.encodeBase64(hash)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return pswSHA; } }
标签:
原文地址:http://www.cnblogs.com/live365wang/p/4684050.html