import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
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 java.io.InputStream;
import java.util.Hashtable;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class LdapVerify {
public boolean connehct(String username, String password) {
String ip = "";
String port = "";
String timeOut = "";
String adminDn = "";
String adminPassword = "";
String url = String.format("ldaps://%s:%s", ip, port);
Hashtable<String, String> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, url);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, adminDn);
env.put(Context.SECURITY_CREDENTIALS, adminPassword);
env.put(Context.SECURITY_PROTOCOL, "ssl");
env.put("com.sun.jndi.ldap.connect.timeout", "3000");
try {
LdapContext ldapContext = new InitialLdapContext(env, null);
String searchBase = "OU=All Users,DC=demo,DC=com";
String searchFilter = "(sAMAccountName=" + username + ")";
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> results = ldapContext.search(searchBase, searchFilter, searchControls);
if (results.hasMore()) {
SearchResult result = results.next();
String userDn = result.getNameInNamespace();
log.info("LDAP登录, 找到用户 DN: " + userDn);
Hashtable<String, String> userEnv = new Hashtable<>();
userEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
userEnv.put(Context.PROVIDER_URL, url);
userEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
userEnv.put(Context.SECURITY_PRINCIPAL, userDn);
userEnv.put(Context.SECURITY_CREDENTIALS, password);
userEnv.put(Context.SECURITY_PROTOCOL, "ssl");
userEnv.put("com.sun.jndi.ldap.connect.timeout", "3000");
try {
new InitialLdapContext(userEnv, null).close();
log.info("LDAP登录, 用户验证成功 {}", username);
return true;
}
catch (Exception e) {
log.error("LDAP登录, 用户验证失败", username);
return false;
}
}
log.error("LDAP登录, 找不到用户 DN {} ", username);
return false;
}
catch (NamingException e) {
log.error("LDAP登录, 找用户异常 DN {} {} ", username, e.getMessage(), e);
return false;
}
}
}