use of javax.naming.directory.SearchResult in project Payara by payara.
the class LDAPRealm method userSearch.
/**
* Do anonymous search for the user. Should be unique if exists.
*/
private String userSearch(DirContext ctx, String baseDN, String filter) {
if (_logger.isLoggable(Level.FINEST)) {
_logger.log(Level.FINE, "search: baseDN: " + baseDN + " filter: " + filter);
}
String foundDN = null;
NamingEnumeration namingEnum = null;
SearchControls ctls = new SearchControls();
ctls.setReturningAttributes(_dnOnly);
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
ctls.setCountLimit(1);
try {
namingEnum = ctx.search(baseDN, filter, ctls);
if (namingEnum.hasMore()) {
SearchResult res = (SearchResult) namingEnum.next();
StringBuffer sb = new StringBuffer();
// for dn name with '/'
CompositeName compDN = new CompositeName(res.getName());
String ldapDN = compDN.get(0);
sb.append(ldapDN);
if (res.isRelative()) {
sb.append(",");
sb.append(baseDN);
}
foundDN = sb.toString();
if (_logger.isLoggable(Level.FINEST)) {
_logger.log(Level.FINE, "Found user DN: " + foundDN);
}
}
} catch (Exception e) {
_logger.log(Level.WARNING, "ldaprealm.searcherror", filter);
_logger.log(Level.WARNING, "security.exception", e);
} finally {
if (namingEnum != null) {
try {
namingEnum.close();
} catch (Exception ex) {
}
}
}
return foundDN;
}
use of javax.naming.directory.SearchResult in project perun by CESNET.
the class ExtSourceEGISSO method getGroupSubjects.
@Override
public List<Map<String, String>> getGroupSubjects(Map<String, String> attributes) throws InternalErrorException {
List<Map<String, String>> subjects = new ArrayList<>();
NamingEnumeration<SearchResult> results = null;
String query = attributes.get(GroupsManager.GROUPMEMBERSQUERY_ATTRNAME);
String base = "ou=People,dc=egi,dc=eu";
List<String> ldapGroupSubjects = new ArrayList<>();
try {
SearchControls controls = new SearchControls();
controls.setTimeLimit(5000);
results = getContext().search(base, query, controls);
while (results.hasMore()) {
SearchResult searchResult = results.next();
subjects.add(processResultToSubject(searchResult));
}
} catch (NamingException e) {
log.error("LDAP exception during query {}.", query);
throw new InternalErrorException("LDAP exception during running query " + query, e);
} finally {
try {
if (results != null) {
results.close();
}
} catch (Exception e) {
log.error("LDAP exception during closing result, while running query '{}'", query);
throw new InternalErrorException(e);
}
}
return subjects;
}
use of javax.naming.directory.SearchResult in project simba-os by cegeka.
the class ActiveDirectoryLoginModuleTest method injection.
@Test
@SuppressWarnings("unchecked")
public void injection() throws Exception {
when(configurationService.getValue(SimbaConfigurationParameter.ENABLE_AD_GROUPS)).thenReturn(Boolean.FALSE);
Map<String, String> options = new HashMap<>();
options.put("primaryServer", "localhost:389");
options.put("baseDN", "'dc=rsvzinasti,dc=be'");
options.put("filter", "(&(objectClass=person)(sAMAccountName=%USERNAME%))");
options.put("searchScope", "subtree");
options.put("authDomain", "rsvzinasti.be");
options.put("authAttr", "sAMAccountName");
options.put("securityLevel", "simple");
NamingEnumeration attrsNamingEnumeration = mock(NamingEnumeration.class);
when(attrsNamingEnumeration.hasMore()).thenReturn(true);
Attributes attrs = mock(Attributes.class);
when(attrs.getAll()).thenReturn(attrsNamingEnumeration);
SearchResult searchResult = mock(SearchResult.class);
when(searchResult.getName()).thenReturn(null);
when(searchResult.getAttributes()).thenReturn(attrs);
NamingEnumeration<SearchResult> searchResultNamingEnumeration = mock(NamingEnumeration.class);
when(searchResultNamingEnumeration.hasMoreElements()).thenReturn(true).thenReturn(false);
when(searchResultNamingEnumeration.next()).thenReturn(searchResult);
ArgumentCaptor<String> searchFilter = ArgumentCaptor.forClass(String.class);
final LdapContext ldapContext = mock(LdapContext.class);
when(ldapContext.search(eq("'dc=rsvzinasti,dc=be'"), searchFilter.capture(), any(SearchControls.class))).thenReturn(searchResultNamingEnumeration);
ActiveDirectoryLoginModule loginModule = new ActiveDirectoryLoginModule() {
@Override
protected LdapContext tryPrimaryContext(Hashtable<String, String> env) {
return ldapContext;
}
};
loginModule.setUsername(" u\\*() ");
loginModule.setPassword(" p\\*() ");
loginModule.initialize(new Subject(), mock(CallbackHandler.class), Collections.emptyMap(), options);
boolean result = loginModule.verifyLoginData();
assertThat(result).isTrue();
assertThat(searchFilter.getValue()).isEqualTo("(&(objectClass=person)(sAMAccountName= u5c2a282900 ))");
}
use of javax.naming.directory.SearchResult in project tomcat by apache.
the class JNDIRealm method getUserBySearch.
/**
* Search the directory to return a User object containing
* information about the user with the specified username, if
* found in the directory; otherwise return <code>null</code>.
*
* @param context The directory context
* @param username The username
* @param attrIds String[]containing names of attributes to retrieve.
* @return the User object
* @exception NamingException if a directory server error occurs
*/
protected User getUserBySearch(DirContext context, String username, String[] attrIds) throws NamingException {
if (username == null || userSearchFormat == null)
return null;
// Form the search filter
String filter = userSearchFormat.format(new String[] { username });
// Set up the search controls
SearchControls constraints = new SearchControls();
if (userSubtree) {
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
} else {
constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
constraints.setCountLimit(sizeLimit);
constraints.setTimeLimit(timeLimit);
// Specify the attributes to be retrieved
if (attrIds == null)
attrIds = new String[0];
constraints.setReturningAttributes(attrIds);
NamingEnumeration<SearchResult> results = context.search(userBase, filter, constraints);
try {
// Fail if no entries found
try {
if (results == null || !results.hasMore()) {
return null;
}
} catch (PartialResultException ex) {
if (!adCompat)
throw ex;
else
return null;
}
// Get result for the first entry found
SearchResult result = results.next();
// Check no further entries were found
try {
if (results.hasMore()) {
if (containerLog.isInfoEnabled())
containerLog.info("username " + username + " has multiple entries");
return null;
}
} catch (PartialResultException ex) {
if (!adCompat)
throw ex;
}
String dn = getDistinguishedName(context, userBase, result);
if (containerLog.isTraceEnabled())
containerLog.trace(" entry found for " + username + " with dn " + dn);
// Get the entry's attributes
Attributes attrs = result.getAttributes();
if (attrs == null)
return null;
// Retrieve value of userPassword
String password = null;
if (userPassword != null)
password = getAttributeValue(userPassword, attrs);
String userRoleAttrValue = null;
if (userRoleAttribute != null) {
userRoleAttrValue = getAttributeValue(userRoleAttribute, attrs);
}
// Retrieve values of userRoleName attribute
ArrayList<String> roles = null;
if (userRoleName != null)
roles = addAttributeValues(userRoleName, attrs, roles);
return new User(username, dn, password, roles, userRoleAttrValue);
} finally {
if (results != null) {
results.close();
}
}
}
use of javax.naming.directory.SearchResult in project zeppelin by apache.
the class ActiveDirectoryGroupRealm method getRoleNamesForUser.
private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException {
Set<String> roleNames = new LinkedHashSet<>();
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String userPrincipalName = username;
if (this.principalSuffix != null && userPrincipalName.indexOf('@') < 0) {
userPrincipalName += principalSuffix;
}
String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))";
Object[] searchArguments = new Object[] { userPrincipalName };
NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls);
while (answer.hasMoreElements()) {
SearchResult sr = (SearchResult) answer.next();
if (log.isDebugEnabled()) {
log.debug("Retrieving group names for user [" + sr.getName() + "]");
}
Attributes attrs = sr.getAttributes();
if (attrs != null) {
NamingEnumeration ae = attrs.getAll();
while (ae.hasMore()) {
Attribute attr = (Attribute) ae.next();
if (attr.getID().equals("memberOf")) {
Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr);
if (log.isDebugEnabled()) {
log.debug("Groups found for user [" + username + "]: " + groupNames);
}
Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames);
roleNames.addAll(rolesForGroups);
}
}
}
}
return roleNames;
}
Aggregations