List of usage examples for javax.naming.directory SearchControls SearchControls
public SearchControls()
From source file:edu.internet2.middleware.psp.ldap.LdapSpmlTarget.java
/** {@inheritDoc} */ public void execute(SearchRequest searchRequest, SearchResponse searchResponse) { // query/*from w ww . java2s. co m*/ Query query = searchRequest.getQuery(); // query filter // TODO support QueryClause other than our own String filter = null; for (QueryClause queryClause : query.getQueryClauses()) { if (queryClause instanceof HasReference) { HasReference hasReference = (HasReference) queryClause; if (hasReference.getTypeOfReference() != null && hasReference.getToPsoID() != null && hasReference.getToPsoID().getID() != null) { filter = "(" + hasReference.getTypeOfReference() + "=" + hasReference.getToPsoID().getID() + ")"; // TODO what do we do with hasReference.getReferenceData(); ? } } else if (queryClause instanceof Filter) { FilterItem filterItem = ((Filter) queryClause).getItem(); if (filterItem instanceof EqualityMatch) { String name = ((EqualityMatch) filterItem).getName(); String value = ((EqualityMatch) filterItem).getValue().getValue(); filter = "(" + name + "=" + value + ")"; } } else { fail(searchResponse, ErrorCode.MALFORMED_REQUEST, "Unsupported query."); return; } } if (DatatypeHelper.isEmpty(filter)) { fail(searchResponse, ErrorCode.MALFORMED_REQUEST, "A filter is required."); return; } // query base if (query.getBasePsoID() == null || query.getBasePsoID().getID() == null) { fail(searchResponse, ErrorCode.MALFORMED_REQUEST, "A basePsoID is required."); return; } String base = query.getBasePsoID().getID(); SearchControls searchControls = new SearchControls(); // query scope Scope scope = query.getScope(); if (scope != null) { searchControls.setSearchScope(PSPUtil.getScope(scope)); } ReturnData returnData = searchRequest.getReturnData(); if (returnData == null) { returnData = ReturnData.EVERYTHING; } // attributes to return String[] retAttrs = getPSP().getNames(getId(), returnData).toArray(new String[] {}); searchControls.setReturningAttributes(retAttrs); Ldap ldap = null; try { ldap = ldapPool.checkOut(); LOG.debug("Target '{}' - Search will return attributes '{}'", getId(), Arrays.asList(retAttrs)); LOG.debug("Target '{}' - Searching '{}'", getId(), PSPUtil.toString(searchRequest)); Iterator<SearchResult> searchResults = ldap.search(base, new SearchFilter(filter), searchControls); LOG.debug("Target '{}' - Searched '{}'", getId(), PSPUtil.toString(searchRequest)); SortedLdapBeanFactory ldapBeanFactory = new SortedLdapBeanFactory(); LdapResult ldapResult = ldapBeanFactory.newLdapResult(); ldapResult.addEntries(searchResults); Collection<LdapEntry> entries = ldapResult.getEntries(); LOG.debug("Target '{}' - Search found {} entries.", getId(), entries.size()); for (LdapEntry entry : entries) { searchResponse.addPSO(getPSO(entry, returnData)); } if (logLdif) { Ldif ldif = new Ldif(); LOG.info("Target '{}' - LDIF\n{}", getId(), ldif.createLdif(ldapResult)); } } catch (NameNotFoundException e) { fail(searchResponse, ErrorCode.NO_SUCH_IDENTIFIER, e); } catch (NamingException e) { fail(searchResponse, ErrorCode.CUSTOM_ERROR, e); } catch (LdapPoolException e) { fail(searchResponse, ErrorCode.CUSTOM_ERROR, e); } catch (Spml2Exception e) { fail(searchResponse, ErrorCode.CUSTOM_ERROR, e); } catch (PspException e) { fail(searchResponse, ErrorCode.CUSTOM_ERROR, e); } finally { ldapPool.checkIn(ldap); } }
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 ww w .j av a2 s.co m 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.pentaho.test.platform.plugin.services.security.userrole.ldap.DefaultLdapUserRoleListServiceTest.java
/** * Search for all users starting at <code>ou=groups</code>, looking for objects with * <code>(&(objectClass=groupOfUniqueNames)(cn={0}))</code>, and extracting the <code>uid</code> token of the * <code>uniqueMember</code> attribute. This search implies that the schema is setup such that a user's roles come * from that user's DN being present in the <code>uniqueMember</code> attribute of a child object under the * <code>ou=groups</code> object. * /*from ww w. j av a 2s . c o m*/ * @throws Exception */ @Test public void testGetUsernamesInRole4() throws Exception { SearchControls con1 = new SearchControls(); con1.setReturningAttributes(new String[] { "uniqueMember" }); //$NON-NLS-1$ LdapSearchParamsFactory paramFactory = new LdapSearchParamsFactoryImpl("ou=groups", //$NON-NLS-1$ "(&(objectClass=groupOfUniqueNames)(cn={0}))", con1); //$NON-NLS-1$ Transformer transformer1 = new SearchResultToAttrValueList("uniqueMember", "uid"); //$NON-NLS-1$ //$NON-NLS-2$ GrantedAuthorityToString transformer2 = new GrantedAuthorityToString(); LdapSearch usernamesInRoleSearch = new GenericLdapSearch(getContextSource(), paramFactory, transformer1, transformer2); SearchControls con2 = new SearchControls(); con2.setReturningAttributes(new String[] { "uid" }); //$NON-NLS-1$ LdapSearchParamsFactory paramFactory2 = new LdapSearchParamsFactoryImpl("ou=users", //$NON-NLS-1$ "(businessCategory=cn={0}*)", con2); //$NON-NLS-1$ Transformer transformer3 = new SearchResultToAttrValueList("uid"); //$NON-NLS-1$ GrantedAuthorityToString transformer4 = new GrantedAuthorityToString(); LdapSearch usernamesInRoleSearch2 = new GenericLdapSearch(getContextSource(), paramFactory2, transformer3, transformer4); Set searches = new HashSet(); searches.add(usernamesInRoleSearch); searches.add(usernamesInRoleSearch2); UnionizingLdapSearch unionSearch = new UnionizingLdapSearch(searches); unionSearch.afterPropertiesSet(); DefaultLdapUserRoleListService userRoleListService = getDefaultLdapUserRoleListService(); userRoleListService.setUsernamesInRoleSearch(unionSearch); List<String> res = userRoleListService.getUsersInRole(null, "DEV"); //$NON-NLS-1$ assertTrue(res.contains("pat")); //$NON-NLS-1$ assertTrue(res.contains("tiffany")); //$NON-NLS-1$ if (logger.isDebugEnabled()) { logger.debug("results of getUsernamesInRole4() with role=ROLE_DEV: " + res); //$NON-NLS-1$ } res = userRoleListService.getUsersInRole(null, "DEVELOPMENT"); //$NON-NLS-1$ assertTrue(res.contains("pat")); //$NON-NLS-1$ assertTrue(res.contains("tiffany")); //$NON-NLS-1$ if (logger.isDebugEnabled()) { logger.debug("results of getUsernamesInRole4() with role=DEVELOPMENT: " + res); //$NON-NLS-1$ } }
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 . j av a 2 s .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); 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;/*from w w w .j a va2s . 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}/*from www .jav a2s . co m*/ */ @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:org.apache.syncope.fit.core.reference.GroupITCase.java
@Test public void issueSYNCOPE632() { GroupTO groupTO = null;/*from ww w. ja v a 2 s. c o m*/ 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 ww .j ava 2 s . c o m*/ 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//from w w w. ja v a 2 s . co 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; }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
@Override public void doUpdateCredentialByAdmin(String userName, Object newCredential) throws UserStoreException { DirContext dirContext = this.connectionSource.getContext(); DirContext subDirContext = null; // first search the existing user entry. String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String searchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(new String[] { "userPassword" }); NamingEnumeration<SearchResult> namingEnumeration = null; NamingEnumeration passwords = null; try {/*w ww . ja v a 2s. c om*/ namingEnumeration = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControls); // here we assume only one user // TODO: what to do if there are more than one user // there can be only only on user SearchResult searchResult = null; while (namingEnumeration.hasMore()) { searchResult = namingEnumeration.next(); String passwordHashMethod = realmConfig.getUserStoreProperty(PASSWORD_HASH_METHOD); if (!UserCoreConstants.RealmConfig.PASSWORD_HASH_METHOD_PLAIN_TEXT .equalsIgnoreCase(passwordHashMethod)) { Attributes attributes = searchResult.getAttributes(); Attribute userPassword = attributes.get("userPassword"); // When admin changes other user passwords he do not have to // provide the old password. Here it is only possible to have one password, if there // are more every one should match with the given old password passwords = userPassword.getAll(); if (passwords.hasMore()) { byte[] byteArray = (byte[]) passwords.next(); String password = new String(byteArray); if (password.startsWith("{")) { passwordHashMethod = password.substring(password.indexOf('{') + 1, password.indexOf('}')); } } } String dnName = searchResult.getName(); subDirContext = (DirContext) dirContext.lookup(searchBase); Attribute passwordAttribute = new BasicAttribute("userPassword"); passwordAttribute.add( UserCoreUtil.getPasswordToStore((String) newCredential, passwordHashMethod, kdcEnabled)); BasicAttributes basicAttributes = new BasicAttributes(true); basicAttributes.put(passwordAttribute); subDirContext.modifyAttributes(dnName, DirContext.REPLACE_ATTRIBUTE, basicAttributes); } // we check whether both carbon admin entry and ldap connection // entry are the same if (searchResult.getNameInNamespace() .equals(realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_NAME))) { this.connectionSource.updateCredential((String) newCredential); } } catch (NamingException e) { String errorMessage = "Can not access the directory service for user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(passwords); JNDIUtil.closeNamingEnumeration(namingEnumeration); JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(dirContext); } }