前言
最近一个项目需要用到ldap验证,特此记录一下过程。
基本上的API的调用,但是有几个问题点还是要说明一下。
首先,先准备好四个属性:
url= ldap://127.0.0.1:port
base= xxx
username= xxx
password= xxx
连接LDAP
public static LdapContext connetldap() throws Exception {
// 连接Ldap需要的信息
String ldapFactory = "com.sun.jndi.ldap.LdapCtxFactory";
String ldapUrl = "ldap://xxx";// url
String ldapAccount = "xxx"; // 用户名
String ldapPwd = "xxx";//密码
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, ldapFactory);
// LDAP server
env.put(Context.PROVIDER_URL, ldapUrl);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, ldapAccount);
env.put(Context.SECURITY_CREDENTIALS, ldapPwd);
ctx = new InitialLdapContext(env, connCtls);
return ctx;
}
查找信息
连接查找过程可能会出现各种问题,这里推荐两篇博客:
ldap查询语法
LDAP的特定错误
public static void search() throws Exception {
LdapContext ctx = connetldap();
// 设置过滤条件
String filter = "(mail=*)";
// 限制要查询的字段内容
String[] attrPersonArray = { "uid", "userPassword", "displayName", "cn", "sn", "mail", "description"};
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
// 设置将被返回的Attribute
searchControls.setReturningAttributes(attrPersonArray);
// 三个参数分别为:
// 上下文;
// 要搜索的属性,如果为空或 null,则返回目标上下文中的所有对象;
// 控制搜索的搜索控件,如果为 null,则使用默认的搜索控件
NamingEnumeration<SearchResult> answer = ctx.search("你的base", filter, searchControls);
// 输出查到的数据
while (answer.hasMore()) {
SearchResult result = answer.next();
NamingEnumeration<? extends Attribute> all = result.getAttributes().getAll();
while (all.hasMore()) {
Attribute attr = all.next();
System.out.println(attr.getID() + "=" + attr.get());
}
System.out.println("============");
}
}
校验用户名密码
private static String getUserDn(String user) throws Exception{
StringBuilder userDn = new StringBuilder();
connetldap();
try {
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> en = ctx.search("你的base", "查询条件", constraints);
if (en == null || !en.hasMoreElements()) {
System.out.println("未找到该用户");
}
// maybe more than one element
while (en != null && en.hasMoreElements()) {
SearchResult obj = en.nextElement();
if (obj != null) {
userDn.append(obj.getName());
userDn.append("," + "你的base");
} else {
System.out.println(obj);
}
}
} catch (Exception e) {
System.out.println("查找用户时产生异常。");
e.printStackTrace();
}
return userDn.toString();
}
public static boolean authenricate(String user, String password) throws Exception{
boolean valide = false;
String userDn = getUserDn(user);
try {
ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDn);
ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
ctx.reconnect(connCtls);
System.out.println(userDn + " 验证通过");
valide = true;
} catch (AuthenticationException e) {
System.out.println(userDn + " 验证失败");
System.out.println(e.toString());
} catch (NamingException e) {
System.out.println(userDn + " 验证失败");
}
return valide;
}