List of usage examples for javax.naming.directory SearchControls SUBTREE_SCOPE
int SUBTREE_SCOPE
To view the source code for javax.naming.directory SearchControls SUBTREE_SCOPE.
Click Source Link
From source file:com.funambol.LDAP.security.LDAPUserProvisioningOfficer.java
/** * return the user dn of an ldap entry//w ww . j a v a 2 s . c om * * search: base, filter, attrs, user, pass * @return */ protected SearchResult ldapSearch(String bindUser, String bindPass, String base, String filter, String[] attributes) { SearchResult ret = null; Hashtable<String, Object> bindEnv = new Hashtable<String, Object>(11); bindEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); bindEnv.put(Context.PROVIDER_URL, getLdapUrl()); // remove null attributes List<String> goodAttributes = new ArrayList<String>(); for (String s : attributes) { if (s != null) { goodAttributes.add(s); } } // get the DN DirContext authenticationContext; try { SearchControls ctls = new SearchControls(); ctls.setCountLimit(1); ctls.setReturningObjFlag(true); ctls.setReturningAttributes(goodAttributes.toArray(new String[0])); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Authenticate as User and password if (bindUser != null && bindPass != null) { log.debug("NBinding with credential as user: " + bindUser); bindEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); bindEnv.put(Context.SECURITY_PRINCIPAL, bindUser); bindEnv.put(Context.SECURITY_CREDENTIALS, bindPass); } authenticationContext = new InitialDirContext(bindEnv); // %u, %d in baseDN are still expanded NamingEnumeration<SearchResult> answer; try { answer = authenticationContext.search(base, filter, ctls); if (answer.hasMore()) { ret = (SearchResult) answer.next(); } } catch (NamingException e) { log.warn("Error while searching user with filter [" + filter + "]: " + e.getMessage()); } authenticationContext.close(); return ret; } catch (NamingException e) { log.error("Error while creating context: " + e.getMessage()); if (e.getCause() != null) { log.error("Error is: " + e.getCause().getMessage()); } return null; } }
From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java
@Override public void doSetUserClaimValue(String userName, String claimURI, String value, String profileName) throws UserStoreException { // get the LDAP Directory context DirContext dirContext = this.connectionSource.getContext(); DirContext subDirContext = null; // search the relevant user entry by user name String userSearchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(null); NamingEnumeration<SearchResult> returnedResultList = null; String returnedUserEntry = null; try {/*from www . j a v a 2s . com*/ returnedResultList = dirContext.search(escapeDNForSearch(userSearchBase), userSearchFilter, searchControls); // assume only one user is returned from the search // TODO:what if more than one user is returned returnedUserEntry = returnedResultList.next().getName(); } catch (NamingException e) { String errorMessage = "Results could not be retrieved from the directory context for user : " + userName; if (logger.isDebugEnabled()) { logger.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(returnedResultList); } try { Attributes updatedAttributes = new BasicAttributes(true); // if there is no attribute for profile configuration in LDAP, skip // updating it. // get the claimMapping related to this claimURI String attributeName = getClaimAtrribute(claimURI, userName, null); if ("CN".equals(attributeName)) { subDirContext = (DirContext) dirContext.lookup(userSearchBase); subDirContext.rename(returnedUserEntry, "CN=" + value); return; } Attribute currentUpdatedAttribute = new BasicAttribute(attributeName); /* if updated attribute value is null, remove its values. */ if (EMPTY_ATTRIBUTE_STRING.equals(value)) { currentUpdatedAttribute.clear(); } else { String claimSeparator = realmConfig.getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR); if (claimSeparator != null && !claimSeparator.trim().isEmpty()) { userAttributeSeparator = claimSeparator; } if (value.contains(userAttributeSeparator)) { StringTokenizer st = new StringTokenizer(value, userAttributeSeparator); while (st.hasMoreElements()) { String newVal = st.nextElement().toString(); if (newVal != null && newVal.trim().length() > 0) { currentUpdatedAttribute.add(newVal.trim()); } } } else { currentUpdatedAttribute.add(value); } } updatedAttributes.put(currentUpdatedAttribute); // update the attributes in the relevant entry of the directory // store subDirContext = (DirContext) dirContext.lookup(userSearchBase); subDirContext.modifyAttributes(returnedUserEntry, DirContext.REPLACE_ATTRIBUTE, updatedAttributes); } catch (org.wso2.carbon.user.api.UserStoreException e) { String errorMessage = "Error in obtaining claim mapping for user : " + userName; if (logger.isDebugEnabled()) { logger.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } catch (NamingException e) { handleException(e, userName); } finally { JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(dirContext); } }
From source file:org.apereo.portal.groups.ldap.LDAPGroupStore.java
public EntityIdentifier[] searchForEntities(String query, int method, Class type) throws GroupsException { if (type != group && type != iperson) return new EntityIdentifier[0]; // Guarantee that LDAP injection is prevented by replacing LDAP special characters // with escaped versions of the character query = LdapEncoder.filterEncode(query); ArrayList ids = new ArrayList(); switch (method) { case STARTS_WITH: query = query + "*"; break;/*from w ww.ja v a2s . c om*/ case ENDS_WITH: query = "*" + query; break; case CONTAINS: query = "*" + query + "*"; break; } query = namefield + "=" + query; DirContext context = getConnection(); NamingEnumeration userlist = null; SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(new String[] { keyfield }); try { userlist = context.search(usercontext, query, sc); ArrayList keys = new ArrayList(); processLdapResults(userlist, keys); String[] k = (String[]) keys.toArray(new String[0]); for (int i = 0; i < k.length; i++) { ids.add(new EntityIdentifier(k[i], iperson)); } return (EntityIdentifier[]) ids.toArray(new EntityIdentifier[0]); } catch (NamingException nex) { throw new GroupsException("LDAPGroupStore: Unable to perform filter " + query, nex); } }
From source file:org.jasig.portal.groups.ldap.LDAPGroupStore.java
public EntityIdentifier[] searchForEntities(String query, int method, Class type) throws GroupsException { if (type != group && type != iperson) return new EntityIdentifier[0]; ArrayList ids = new ArrayList(); switch (method) { case STARTS_WITH: query = query + "*"; break;/* w w w . j a v a2s . c o m*/ case ENDS_WITH: query = "*" + query; break; case CONTAINS: query = "*" + query + "*"; break; } query = namefield + "=" + query; DirContext context = getConnection(); NamingEnumeration userlist = null; SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(new String[] { keyfield }); try { userlist = context.search(usercontext, query, sc); } catch (NamingException nex) { log.error("LDAPGroupStore: Unable to perform filter " + query, nex); } ArrayList keys = new ArrayList(); processLdapResults(userlist, keys); String[] k = (String[]) keys.toArray(new String[0]); for (int i = 0; i < k.length; i++) { ids.add(new EntityIdentifier(k[i], iperson)); } return (EntityIdentifier[]) ids.toArray(new EntityIdentifier[0]); }
From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java
/** * * {@inheritDoc}// www. jav a 2 s. com */ @Override public String resolveDistinguishedName(final String userId, final AuthenticationDiagnostic diagnostic) throws AuthenticationException { LOGGER.debug("resolveDistinguishedName userId: {}", userId); final SearchControls userSearchCtls = new SearchControls(); userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868 userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName }); final String query = this.userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName + "= userId))"; NamingEnumeration<SearchResult> searchResults = null; SearchResult result = null; InitialDirContext ctx = null; try { ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic); // Execute the user query with an additional condition that ensures only the user with the required ID is // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation searchResults = ctx.search(this.userSearchBase, "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId }, userSearchCtls); if (searchResults.hasMore()) { result = searchResults.next(); final Attributes attributes = result.getAttributes(); final Attribute uidAttribute = attributes.get(this.userIdAttributeName); if (uidAttribute == null) { if (this.errorOnMissingUID) { throw new AlfrescoRuntimeException( "User returned by user search does not have mandatory user id attribute " + attributes); } else { LOGGER.warn("User returned by user search does not have mandatory user id attribute {}", attributes); } } // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will // only resolve this user if the user ID matches else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) { final String name = result.getNameInNamespace(); this.commonCloseSearchResult(result); result = null; return name; } this.commonCloseSearchResult(result); result = null; } final Object[] args = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_LOOKUP_USER, false, args); throw new AuthenticationException("authentication.err.connection.ldap.user.notfound", args, diagnostic); } catch (final NamingException e) { // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory final Object[] args1 = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1); // failed to search final Object[] args = { e.getLocalizedMessage() }; throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic, args, e); } finally { this.commonAfterQueryCleanup(searchResults, result, ctx); } }
From source file:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java
protected boolean organizationExists(String orgId) throws ExecutionException { NamingEnumeration<SearchResult> searchResults = null; try {/*from ww w . jav a2s .c o m*/ searchResults = this.query(LDAPConnector.getSingletonInstance().getInstitutionBaseDN(), new StringBuilder("(& (objectclass=").append(Constants.ldap_ddbOrg_ObjectClass).append(") (") .append(Constants.ldap_ddbOrg_Id).append("=").append(orgId).append("))").toString(), new String[] { Constants.ldap_ddbOrg_Id, "+" }, SearchControls.SUBTREE_SCOPE); if (searchResults.hasMore()) { return true; } else { return false; } } catch (IllegalAccessException ex) { LOG.log(Level.SEVERE, "Connection-Error", ex); throw new ExecutionException(ex.getMessage(), ex.getCause()); } catch (NamingException ne) { LOG.log(Level.SEVERE, "something went wrong while checking if userId exists", ne); throw new ExecutionException(ne.getMessage(), ne.getCause()); } finally { if (searchResults != null) { try { searchResults.close(); } catch (NamingException e) { } } } }
From source file:org.apache.directory.studio.connection.core.io.api.DirectoryApiConnectionWrapper.java
/** * Converts the search scope./*from ww w . j av a2s .c o m*/ * * @param searchControls * the search controls * @return * the associated search scope */ private SearchScope convertSearchScope(SearchControls searchControls) { int scope = searchControls.getSearchScope(); if (scope == SearchControls.OBJECT_SCOPE) { return SearchScope.OBJECT; } else if (scope == SearchControls.ONELEVEL_SCOPE) { return SearchScope.ONELEVEL; } else if (scope == SearchControls.SUBTREE_SCOPE) { return SearchScope.SUBTREE; } else { return SearchScope.SUBTREE; } }
From source file:org.apache.syncope.fit.core.reference.GroupITCase.java
@Test public void issueSYNCOPE632() { GroupTO groupTO = null;/*from ww w.j a va2s . com*/ try { // 1. create new LDAP resource having ConnObjectKey mapped to a derived attribute ResourceTO newLDAP = resourceService.read(RESOURCE_NAME_LDAP); newLDAP.setKey("new-ldap"); newLDAP.setPropagationPrimary(true); MappingTO mapping = newLDAP.getProvision(AnyTypeKind.GROUP.name()).getMapping(); MappingItemTO connObjectKey = mapping.getConnObjectKeyItem(); connObjectKey.setIntMappingType(IntMappingType.GroupDerivedSchema); connObjectKey.setIntAttrName("displayProperty"); mapping.setConnObjectKeyItem(connObjectKey); mapping.setConnObjectLink("'cn=' + displayProperty + ',ou=groups,o=isp'"); MappingItemTO description = new MappingItemTO(); description.setIntMappingType(IntMappingType.GroupKey); description.setExtAttrName("description"); description.setPurpose(MappingPurpose.BOTH); mapping.add(description); newLDAP = createResource(newLDAP); assertNotNull(newLDAP); // 2. create a group and give the resource created above groupTO = getSampleTO("lastGroup" + getUUIDString()); groupTO.getPlainAttrs().add(attrTO("icon", "anIcon")); groupTO.getPlainAttrs().add(attrTO("show", "true")); groupTO.getDerAttrs().add(attrTO("displayProperty", null)); groupTO.getResources().clear(); groupTO.getResources().add("new-ldap"); groupTO = createGroup(groupTO); assertNotNull(groupTO); // 3. update the group GroupMod groupMod = new GroupMod(); groupMod.setKey(groupTO.getKey()); groupMod.getPlainAttrsToRemove().add("icon"); groupMod.getPlainAttrsToUpdate().add(attrMod("icon", "anotherIcon")); groupTO = updateGroup(groupMod); assertNotNull(groupTO); // 4. check that a single group exists in LDAP for the group created and updated above int entries = 0; DirContext ctx = null; try { ctx = getLdapResourceDirContext(null, null); SearchControls ctls = new SearchControls(); ctls.setReturningAttributes(new String[] { "*", "+" }); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> result = ctx.search("ou=groups,o=isp", "(description=" + groupTO.getKey() + ")", ctls); while (result.hasMore()) { result.next(); entries++; } } catch (Exception e) { // ignore } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { // ignore } } } assertEquals(1, entries); } finally { if (groupTO != null) { groupService.delete(groupTO.getKey()); } resourceService.delete("new-ldap"); } }
From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java
private String lookupUserId(String serverName) throws DirectoryServerManagerException { DirContext dirContext;/* w w w . ja v a2 s .c om*/ try { dirContext = this.connectionSource.getContext(); } catch (UserStoreException e) { throw new DirectoryServerManagerException("Unable to retrieve directory connection.", e); } String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); //first search the existing user entry. String searchFilter = getServicePrincipleFilter(serverName); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(new String[] { "uid" }); try { NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, searchFilter, searchControls); // here we assume only one user if (namingEnumeration.hasMore()) { SearchResult searchResult; searchResult = namingEnumeration.next(); Attributes attributes = searchResult.getAttributes(); Attribute userId = attributes.get("uid"); return (String) userId.get(); } else { return null; } } catch (NamingException e) { log.error("Could not find user id for given server " + serverName, e); throw new DirectoryServerManagerException("Could not find user id for given server " + serverName, e); } finally { try { JNDIUtil.closeContext(dirContext); } catch (UserStoreException e) { log.error("Unable to close directory context.", e); } } }
From source file:com.aurel.track.util.LdapUtil.java
/** * Get all ldap groups//w w w.j a v a2s. c o m * * @param siteBean * @param baseDnGroup * @param ldapFilterGroups * @param groupAttributeName * @param groupToMemberReferencesMap * @return * @throws Exception */ public static Map<String, TPersonBean> getLdapGroupsPaged(String baseURL, TSiteBean siteBean, String baseDnGroup, String ldapFilterGroups, String groupAttributeName, Map<String, List<String>> groupToMemberReferencesMap) throws Exception { if (ldapFilterGroups == null || "".equals(ldapFilterGroups) || "*".equals(ldapFilterGroups)) { ldapFilterGroups = "(" + groupAttributeName + "=*)"; } String bindDN = siteBean.getLdapBindDN(); String bindPassword = siteBean.getLdapBindPassword(); LdapContext context = getInitialContext(baseURL + baseDnGroup, bindDN, bindPassword); HashMap<String, TPersonBean> ldapGroupsMap = new HashMap<String, TPersonBean>(); if (context == null) { LOGGER.warn("Context is null"); return ldapGroupsMap; } int recordCount = 0; SearchControls ctls = null; String groupMemberAttributName = ldapMap.get(LDAP_CONFIG.GROUP_MEMBER); if (groupMemberAttributName == null) { groupMemberAttributName = DEFAULT_GROUP_MEMBER; } try { // Activate paged results int pageSize = 5; byte[] cookie = null; context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); int total; // Control the search ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setCountLimit((ApplicationBean.getInstance().getMaxNumberOfFullUsers() + ApplicationBean.getInstance().getMaxNumberOfLimitedUsers()) * 3 + 10); // Don't ask for more than we can handle // anyways do { /* perform the search */ NamingEnumeration<SearchResult> results = context.search("", ldapFilterGroups, ctls); /* for each entry print out name + all attrs and values */ while (results != null && results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); // Attributes atrs = sr.getAttributes(); Attributes attributes = searchResult.getAttributes(); if (attributes == null) { LOGGER.warn("No attributes found in LDAP search result " + searchResult.getName()); return null; } TPersonBean personBean = new TPersonBean(); try { Attribute groupNameAttribute = attributes.get(groupAttributeName); if (groupNameAttribute != null) { String groupName = (String) groupNameAttribute.get(); LOGGER.debug("Groupname: " + groupName); if (groupName == null || "".equals(groupName)) { LOGGER.info("No value for group name attribute " + groupAttributeName); return null; } else { personBean.setLoginName(groupName); ldapGroupsMap.put(personBean.getLoginName(), personBean); } Attribute memberAttribute = attributes.get(groupMemberAttributName); if (memberAttribute != null) { NamingEnumeration<?> members = memberAttribute.getAll(); while (members != null && members.hasMore()) { String memberSearchResult = (String) members.next(); List<String> memberDNList = groupToMemberReferencesMap.get(groupName); if (memberDNList == null) { memberDNList = new ArrayList<String>(); groupToMemberReferencesMap.put(groupName, memberDNList); } memberDNList.add(memberSearchResult); } } else { LOGGER.info("Could not find value(s) for group member attribute " + groupMemberAttributName + " for group " + groupName); } } LOGGER.debug("LDAP entry cn: " + (String) attributes.get("cn").get()); LOGGER.debug("Processed " + personBean.getLoginName() + " (" + personBean.getFirstName() + " " + personBean.getLastName() + ")"); } catch (Exception e) { LOGGER.warn("Problem setting attributes from LDAP: " + e.getMessage()); LOGGER.warn( "This is probably a configuration error in the LDAP mapping section of quartz-jobs.xml"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Stack trace:", e); } } ++recordCount; } // Examine the paged results control response Control[] controls = context.getResponseControls(); if (controls != null) { for (int i = 0; i < controls.length; i++) { if (controls[i] instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i]; total = prrc.getResultSize(); if (total != 0) { LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total + ") *****************\n"); } else { LOGGER.debug( "***************** END-OF-PAGE " + "(total: unknown) ***************\n"); } cookie = prrc.getCookie(); } } } else { LOGGER.debug("No controls were sent from the server"); } // Re-activate paged results context.setRequestControls( new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); } while (cookie != null); } catch (SizeLimitExceededException sle) { if (recordCount < ctls.getCountLimit()) { LOGGER.error("Searching LDAP asked for more entries than permitted by the LDAP server."); LOGGER.error("Size limit exceeded error occurred after record " + recordCount + " with " + sle.getMessage()); LOGGER.error( "You have to ask your LDAP server admin to increase the limit or specify a more suitable search base or filter."); } else { LOGGER.error("Searching LDAP asked for more entries than permitted by the Genji server (" + recordCount + ")."); LOGGER.error( "You have to get more user licenses for Genji or specify a more suitable search base or filter."); } LOGGER.error("The LDAP synchronization is most likely incomplete."); } catch (NamingException e) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } catch (IOException ie) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(ie)); } finally { context.close(); } return ldapGroupsMap; }