import java.util.Hashtable;import javax.naming.Context;import javax.naming.NamingEnumeration;import javax.naming.ldap.InitialLdapContext;import javax.naming.ldap.LdapContext; public class LdapAuth { private String domain; private String ldapHost; private String searchBase; public LdapAuth(){ this.domain = "${domain}"; this.ldapHost = "ldap://${IP}:${PORT}"; this.searchBase = "DC=${DC1},DC=${DC2}"; } public LdapAuth(String domain,String host,String dn){ this.domain = domain; this.ldapHost = host; this.searchBase = dn; } public boolean authLdap(String username,String pass){ String searchFilter = "(&(objectClass=user)(sAMAccountName=" + username + "))"; Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapHost); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, username + "@" + domain); env.put(Context.SECURITY_CREDENTIALS, pass); LdapContext ctxGC = null; boolean ldapUser = false; try { ctxGC = new InitialLdapContext(env,null); NamingEnumeration answer = ctxGC.search(searchBase, searchFilter,null); if (answer!=null) { ldapUser = true; } } catch (Exception e) { // TODO: handle exception } return ldapUser; }
测试:
用户名密码正确: