我需要在身份验证后从LDAP中检索各种值,例如说明,Office等。
我已经能够完成身份验证,但我无法检索其他值。
我应该用什么名字来检索完整的数据?
请帮忙。
我的代码如下:
public boolean authenticate(String userid, String pass, String domain) {
boolean retval = false;
String searchFilter ="(&(objectClass=user)(" + LDAP_UID_ATTR + "=" + userid + "))";
try {
System.out.println("Start: getLDAPAttrs");
NamingEnumeration answer =
getLDAPAttrs(userid, pass, searchFilter, domain);
String uid = "";
while (answer.hasMoreElements()) {
SearchResult sr = (SearchResult)answer.next();
Attributes attrs = sr.getAttributes();
try {
uid = attrs.get(LDAP_UID_ATTR).toString();
System.out.println("uid: " + uid);
System.out.println(attrs.get("mail"));
uid = uid.substring(uid.indexOf(':') + 2);
} catch (Exception err) {
// uid = "";
System.out.println(err.getMessage());
err.printStackTrace();
}
// verify userid
if (userid.equalsIgnoreCase(uid)) {
retval = true;
break;
}
}
} catch (NamingException ne) {
System.out.println("In authenticateWithLDAP, LDAP Authentication NamingException : " +
ne.getMessage());
} catch (Exception ex) {
System.out.println("In authenticateWithLDAP, LDAP Authentication Exception : " +
ex.getMessage());
}
return retval;
// return retval;
}
private NamingEnumeration getLDAPAttrs(String userid, String pass,
String searchFilter,
String domain) throws NamingException,
Exception {
String host = getServerName();
String port = getIP_Port();
String dcPart1 = getDcPart1();
String dcPart2 = getDcPart2();
// String attrUserID = getLDAP_UID_ATTR();
// String attrUserName = getLDAP_UNAME_ATTR();
// set attribute names to obtain value of
String[] returnedAtts = { "sAMAccountName", "cn","mail" };
SearchControls searchCtls = new SearchControls();
searchCtls.setReturningAttributes(returnedAtts);
// specify the search scope
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
// set search base
String searchBase = "DC=" + dcPart1 + ",DC=" + dcPart2;
// set ldap env values
Hashtable environment = new Hashtable();
environment.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port);
environment.put(Context.SECURITY_AUTHENTICATION, "simple");
environment.put(Context.SECURITY_PRINCIPAL, userid + "@" + domain);
environment.put(Context.SECURITY_CREDENTIALS, pass);
// set ldap context
DirContext ctxGC = new InitialDirContext(environment);
// perform search to obtain values
NamingEnumeration answer =
ctxGC.search(searchBase, searchFilter, searchCtls);
return answer;
}
答案 0 :(得分:3)
LDAP客户端通过向服务器发送搜索请求然后读取服务器的响应来检索属性值(在问题中称为“字段”)。搜索请求至少包含以下组件:
base
,one
或subtree
此外,可以与搜索请求一起发送所请求属性的列表。如果未提供请求的属性列表,则许多LDAP SDK将仅返回所有用户属性而不返回操作属性。在这种情况下,请求属性description
和office
以及其他所需的属性。
符合LDAP的服务器强制实施访问控制方案,该方案可能导致服务器不返回某些属性。请咨询LDAP管理员,以确定LDAP客户端连接的身份验证状态是否具有访问所需属性的权限。
ldapsearch
命令行工具,但其概念与编程访问相同。答案 1 :(得分:0)
我发现了什么问题。
我必须在返回的属性中包含参数:
String[] returnedAtts = { "sAMAccountName", "cn","mail" };
或
String[] returnedAtts = { "sAMAccountName", "cn","mail","description" };
然后在获取属性时使用其值。
感谢