提示:以下是本篇文章正文内容,下面案例可供参考
一、如何通过Ldap认证?
public static List<SysUser> readLdap() {
// 域地址
String url = "xxx";
String factory = "com.sun.jndi.ldap.LdapCtxFactory";
// 用户名
String root = "登录用户名@pmish-tech.com";
// 密码
String pwd = "登录密码";
String simple = "simple";
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
env.put(Context.PROVIDER_URL, url);
env.put(Context.SECURITY_AUTHENTICATION, simple);
env.put(Context.SECURITY_PRINCIPAL, root);
env.put(Context.SECURITY_CREDENTIALS, pwd);
LdapContext ctx = null;
Control[] connCtls = null;
try {
ctx = new InitialLdapContext(env, connCtls);
log.info("认证成功");
} catch (javax.naming.AuthenticationException e) {
log.info("认证失败:");
e.printStackTrace();
return null;
} catch (Exception e) {
log.info("认证出错:");
e.printStackTrace();
return null;
}
// 认证结束后,获取用户信息
ArrayList<SysUser> AllUser = new ArrayList<>();
try {
// CN=用户名,OU=组织单位,DC=域
String base = "OU=xxxx,DC=xxxx,DC=xxx";
//过滤条件
String filter = "xxx";
// 查询的参数
String[] attrPersonArray = {"用户名", "邮箱", "别名"};
//搜索控件
SearchControls searchControls = new SearchControls();
//搜索范围
searchControls.setSearchScope(2);
searchControls.setReturningAttributes(attrPersonArray);
//1.要搜索的上下文或对象的名称;2.过滤条件,可为null,默认搜索所有信息;3.搜索控件,可为null,使用默认的搜索控件
NamingEnumeration<SearchResult> answer = ctx.search(base, filter, searchControls);
ArrayList<SysUser> userInfo = getUserInfo(answer);
AllUser.addAll(userInfo);
// 输出这次获取了多少用户信息
log.info(AllUser.size());
} catch (Exception e) {
e.printStackTrace();
}
try {
if (ctx != null)
ctx.close();
} catch (NamingException e) {
e.printStackTrace()
}
return AllUser;
}
二、如何获取用户信息?
代码如下(示例):
private static ArrayList<SysUser> getUserInfo(NamingEnumeration<SearchResult> answer) throws NamingException {
ArrayList<SysUser> lm = new ArrayList<>();
while (answer.hasMore()) {
SearchResult result = answer.next();
NamingEnumeration<? extends Attribute> attrs = result.getAttributes().getAll();
SysUser ldapEntity = new SysUser();
Map<String, Object> map = new HashMap<String, Object>();
while (attrs.hasMore()) {
Attribute attr = attrs.next();
String key = attr.getID();
String value = attr.get().toString();
if ("用户名".equals(key)) {
ldapEntity.set用户名(value);
} else if ("邮箱".equals(key)) {
ldapEntity.set邮箱(value);
} else if ("别名".equals(key)) {
ldapEntity.set别名(value);
}
map.put(attr.getID(), attr.get());
}
lm.add(ldapEntity);
}
return lm;
}