我无法找到用户所属的角色,我尝试了以下代码,它提供了很多属性,但我感兴趣的是用户在某个应用中属于哪些角色。
我要搜索的用户属于以下两个组(userrole和adminrole)。我如何检索这些信息?
DN:cn = userrole,ou = roles,ou = appname,ou = apps,ou = groups,dc = example,dc = no
DN:cn = adminrole,ou = roles,ou = appname,ou = apps,ou = groups,dc = example,dc = no
private final String host = "host.example.com";
private final int port = 389;
private final String bindDn = "uid=appname,ou=systems,dc=example,dc=no";
private final String password = "password";
private final String searchDn = "dc=example,dc=no";
public SearchResultEntry getUserDetails(String username) {
try {
final LDAPConnection connection = new LDAPConnection(host, port,
bindDn, password);
SearchResult searchResults;
searchResults = connection.search(searchDn, SearchScope.SUB,
"(uid=" + username + ")", "+");
if (searchResults.getEntryCount() == 1) {
SearchResultEntry entry = searchResults.getSearchEntries().get(
0);
connection.close();
return entry;
} else {
LOGGER.error("NOT FOUND!");
connection.close();
return null;
}
} catch (LDAPException e) {
LOGGER.error("Exception");
return null;
}
}
答案 0 :(得分:1)
使用以下功能。
假设您使用SUN LDAP(使用uid
):
<强>被修改强>
private boolean isGroupContainUser(LDAPConnection ldapConnection, String groupDn, String userDn) throws LDAPException {
boolean ret = false;
Entry groupEntry = ldapConnection.getEntry(groupDn);
String[] memberValues = groupEntry.getAttributeValues("uniquemember");
if (memberValues != null) {
DN ldapUserDn = new DN(userDn);
for (String memberEntryDnString : memberValues) {
DN memberEntryDn = new DN(memberEntryDnString);
if (memberEntryDn.equals(ldapUserDn)) {
ret = true;
break;
}
}
}
return ret;
}
答案 1 :(得分:0)
服务器可能支持memberOf
或isMemberOf
。这些属性(在大多数服务器中,这些属性是虚拟,也就是说,它们不占用任何存储并在客户端请求时生成),它们在对象中的存在表示对象的组成员资格。以下示例假设服务器支持isMemberOf
属性:
String[] getGroupMembership() {
try {
// SSL can be supported by using a SocketFactory
SocketFactory socketFactory = createSocketFactory();
LDAPConnectionOptions options = new LDAPConnectionOptions();
options.setConnectTimeoutMillis(connectTimeoutMillis);
// Try to connect to a single server. It is also possible to use
// a 'ServerSet' for support of multiple servers.
LDAPConnection ldapConnection =
new LDAPConnection(socketFactory,options,hostname,port,
userDN,userPassword);
try {
// Some broken directory servers, most notably the old Sun
// directory servers, do not support the legal filter "(&)".
// If this is the case, use the present filter "(objectClass=*)"
// instead.
SearchRequest searchRequest =
new SearchRequest(userDN,SearchScope.BASE,"(&)","isMemberOf");
searchRequest.setResponseTimeoutMillis(responseTimeoutMillis);
SearchResult searchResult = ldapConnection.search(searchRequest);
if(searchResult.getEntryCount() == 1) {
Entry entry = searchResult.getSearchEntry(userDN);
return getAttributeValues("isMemberOf");
}
} catch(LDAPException ex) {
// Handle the exception
} finally {
ldapConnection.close();
}
} catch(LDAPException ldapException) {
// Handle the connection exception here
}
return null;
}