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: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 {/*from w w w.jav a 2 s . c o m*/ 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); } }
From source file:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java
/** * Searches the remote directory for the user's entry and returns its distinguished name * string.//from w w w.j a v a2 s. co m * * @param userId * the ID of the user whose DN is to be retrieved * @param context * the directory context from which to retrieve the user's DN * @return String * @throws NamingException */ protected String findUserDn(String userId, DirContext context) throws NamingException { String userDn = null; for (MessageFormat userSearchPattern : userSearchPatterns) { try { String searchFilter = userSearchPattern.format(new String[] { userId }); SearchControls constraints = new SearchControls(); constraints.setSearchScope( searchUserSubtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE); constraints.setTimeLimit(userSearchTimeout); NamingEnumeration<SearchResult> results = context.search(userSearchBase, searchFilter, constraints); SearchResult result = null; try { if ((results != null) && results.hasMore()) { result = results.next(); // Make sure only one entry exists for the requested user if (results.hasMore()) { log.warn("Multiple entries found for user: " + userId); result = null; } } } catch (PartialResultException e) { // Ignore partial result errors - most likely due to ActiveDirectory referrals } if (result != null) { userDn = result.getNameInNamespace(); break; } } catch (NameNotFoundException e) { // Ignore and keep searching } } return userDn; }
From source file:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java
protected boolean licensedOganizationExists(String orgId) throws ExecutionException { NamingEnumeration<SearchResult> searchResults = null; try {//w ww.j a va 2 s .c o m searchResults = this.query(LDAPConnector.getSingletonInstance().getLicensedInstitutionsBaseDN(), 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.georchestra.console.ds.AccountDaoImpl.java
@Override public List<Account> findByShadowExpire() { SearchControls sc = new SearchControls(); sc.setReturningAttributes(UserSchema.ATTR_TO_RETRIEVE); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); AndFilter filter = new AndFilter(); filter.and(new EqualsFilter("objectClass", "shadowAccount")); filter.and(new EqualsFilter("objectClass", "inetOrgPerson")); filter.and(new EqualsFilter("objectClass", "organizationalPerson")); filter.and(new EqualsFilter("objectClass", "person")); filter.and(new PresentFilter("shadowExpire")); return ldapTemplate.search(DistinguishedName.EMPTY_PATH, filter.encode(), sc, attributMapper); }
From source file:org.wso2.carbon.identity.agent.userstore.manager.ldap.LDAPUserStoreManager.java
/** * {@inheritDoc}/*from w w w .j a v a 2 s .c om*/ */ @Override public boolean doCheckIsUserInRole(String userName, String roleName) throws UserStoreException { boolean debug = log.isDebugEnabled(); String searchBases = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // read the roles with this membership property String searchFilter = userStoreProperties.get(LDAPConstants.GROUP_NAME_LIST_FILTER); String membershipProperty = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE); if (membershipProperty == null || membershipProperty.length() < 1) { throw new UserStoreException("Please set membership attribute"); } String roleNameProperty = userStoreProperties.get(LDAPConstants.GROUP_NAME_ATTRIBUTE); String userDNPattern = userStoreProperties.get(LDAPConstants.USER_DN_PATTERN); String nameInSpace; if (org.apache.commons.lang.StringUtils.isNotEmpty(userDNPattern) && !userDNPattern.contains(CommonConstants.XML_PATTERN_SEPERATOR)) { nameInSpace = MessageFormat.format(userDNPattern, escapeSpecialCharactersForDN(userName)); } else { nameInSpace = this.getNameInSpaceForUserName(userName); } String membershipValue; if (nameInSpace != null) { try { LdapName ldn = new LdapName(nameInSpace); membershipValue = escapeLdapNameForFilter(ldn); } catch (InvalidNameException e) { log.error("Error while creating LDAP name from: " + nameInSpace); throw new UserStoreException( "Invalid naming org.wso2.carbon.identity.agent.outbound.exception for : " + nameInSpace, e); } } else { return false; } searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + "))"; String returnedAtts[] = { roleNameProperty }; searchCtls.setReturningAttributes(returnedAtts); if (debug) { log.debug("Do check whether the user : " + userName + " is in role: " + roleName); log.debug("Search filter : " + searchFilter); for (String retAttrib : returnedAtts) { log.debug("Requesting attribute: " + retAttrib); } } DirContext dirContext = null; NamingEnumeration<SearchResult> answer = null; try { dirContext = connectionSource.getContext(); if (debug) { log.debug("Do check whether the user: " + userName + " is in role: " + roleName); log.debug("Search filter: " + searchFilter); for (String retAttrib : returnedAtts) { log.debug("Requesting attribute: " + retAttrib); } } searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + ") (" + roleNameProperty + "=" + escapeSpecialCharactersForFilter(roleName) + "))"; // handle multiple search bases String[] searchBaseArray = searchBases.split(CommonConstants.XML_PATTERN_SEPERATOR); for (String searchBase : searchBaseArray) { answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls); if (answer.hasMoreElements()) { if (debug) { log.debug("User: " + userName + " in role: " + roleName); } return true; } if (debug) { log.debug("User: " + userName + " NOT in role: " + roleName); } } } catch (NamingException e) { if (log.isDebugEnabled()) { log.debug(e.getMessage(), e); } } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } return false; }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * {@inheritDoc}// w w w .j a v a 2 s . c o m */ @Override public boolean doCheckIsUserInRole(String userName, String roleName) throws UserStoreException { boolean debug = log.isDebugEnabled(); String searchBases = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // read the roles with this membership property String searchFilter = userStoreProperties.get(LDAPConstants.GROUP_NAME_LIST_FILTER); String membershipProperty = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE); if (membershipProperty == null || membershipProperty.length() < 1) { throw new UserStoreException("Please set membership attribute"); } String roleNameProperty = userStoreProperties.get(LDAPConstants.GROUP_NAME_ATTRIBUTE); String userDNPattern = userStoreProperties.get(LDAPConstants.USER_DN_PATTERN); String nameInSpace; if (org.apache.commons.lang.StringUtils.isNotEmpty(userDNPattern) && !userDNPattern.contains(CommonConstants.XML_PATTERN_SEPERATOR)) { nameInSpace = MessageFormat.format(userDNPattern, escapeSpecialCharactersForDN(userName)); } else { nameInSpace = this.getNameInSpaceForUserName(userName); } String membershipValue; if (nameInSpace != null) { try { LdapName ldn = new LdapName(nameInSpace); membershipValue = escapeLdapNameForFilter(ldn); } catch (InvalidNameException e) { log.error("Error while creating LDAP name from: " + nameInSpace); throw new UserStoreException("Invalid naming exception for : " + nameInSpace, e); } } else { return false; } searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + "))"; String returnedAtts[] = { roleNameProperty }; searchCtls.setReturningAttributes(returnedAtts); if (debug) { log.debug("Do check whether the user : " + userName + " is in role: " + roleName); log.debug("Search filter : " + searchFilter); for (String retAttrib : returnedAtts) { log.debug("Requesting attribute: " + retAttrib); } } DirContext dirContext = null; NamingEnumeration<SearchResult> answer = null; try { dirContext = connectionSource.getContext(); if (debug) { log.debug("Do check whether the user: " + userName + " is in role: " + roleName); log.debug("Search filter: " + searchFilter); for (String retAttrib : returnedAtts) { log.debug("Requesting attribute: " + retAttrib); } } searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + ") (" + roleNameProperty + "=" + escapeSpecialCharactersForFilter(roleName) + "))"; // handle multiple search bases String[] searchBaseArray = searchBases.split(CommonConstants.XML_PATTERN_SEPERATOR); for (String searchBase : searchBaseArray) { answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls); if (answer.hasMoreElements()) { if (debug) { log.debug("User: " + userName + " in role: " + roleName); } return true; } if (debug) { log.debug("User: " + userName + " NOT in role: " + roleName); } } } catch (NamingException e) { if (log.isDebugEnabled()) { log.debug(e.getMessage(), e); } } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } return false; }
From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
protected boolean isExistingLDAPRole(RoleContext context) throws UserStoreException { boolean debug = log.isDebugEnabled(); boolean isExisting = false; String roleName = context.getRoleName(); if (debug) {/* w ww. ja va2 s.c o m*/ log.debug("Searching for role: " + roleName); } String searchFilter = ((LDAPRoleContext) context).getListFilter(); String roleNameProperty = ((LDAPRoleContext) context).getRoleNameProperty(); searchFilter = "(&" + searchFilter + "(" + roleNameProperty + "=" + escapeSpecialCharactersForFilter(roleName) + "))"; String searchBases = ((LDAPRoleContext) context).getSearchBase(); if (debug) { log.debug("Using search filter: " + searchFilter); } SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setReturningAttributes(new String[] { roleNameProperty }); NamingEnumeration<SearchResult> answer = null; DirContext dirContext = null; try { dirContext = connectionSource.getContext(); // with DN patterns if (((LDAPRoleContext) context).getRoleDNPatterns().size() > 0) { for (String pattern : ((LDAPRoleContext) context).getRoleDNPatterns()) { if (debug) { log.debug("Using pattern: " + pattern); } pattern = MessageFormat.format(pattern.trim(), escapeSpecialCharactersForDN(roleName)); try { answer = dirContext.search(escapeDNForSearch(pattern), searchFilter, searchCtls); } catch (NamingException e) { if (log.isDebugEnabled()) { log.debug(e); } // ignore } if (answer != null && answer.hasMoreElements()) { return true; } } } //try out with handle multiple search bases String[] roleSearchBaseArray = searchBases.split("#"); for (String searchBase : roleSearchBaseArray) { // no DN Patterns found if (debug) { log.debug("Searching in " + searchBase); } try { answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls); if (answer.hasMoreElements()) { isExisting = true; break; } } catch (NamingException e) { if (log.isDebugEnabled()) { log.debug(e); } // ignore } } } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } if (debug) { log.debug("Is role: " + roleName + " exist: " + isExisting); } return isExisting; }
From source file:com.nridge.core.app.ldap.ADQuery.java
/** * This method will perform multiple queries into Active Directory * in order to resolve what groups a user is a member of. The * logic will identify nested groups and add them to the table. * <p>/*from w w w .j a va2 s . c o m*/ * The LDAP_ACCOUNT_NAME field must be populated in the user bag * prior to invoking this method. Any site specific fields can be * assigned to the user bag will be included in the attribute query. * </p> * <p> * Any site specific fields can be assigned to the group bag will * be included in the attribute query. * </p> * * @param aUserBag Active Directory user attributes. * @param aGroupBag Active Directory group attributes. * * @return Table of groups that the user is a member of. * * @throws NSException Thrown if an LDAP naming exception is occurs. */ @SuppressWarnings("StringConcatenationInsideStringBufferAppend") public DataTable loadUserGroupsByAccountName(DataBag aUserBag, DataBag aGroupBag) throws NSException { byte[] objectSid; DataBag groupBag; Attribute responseAttribute; String fieldName, fieldValue; Logger appLogger = mAppMgr.getLogger(this, "loadUserGroupsByAccountName"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); if (mLdapContext == null) { String msgStr = "LDAP context has not been established."; appLogger.error(msgStr); throw new NSException(msgStr); } // First, we will populate our user bag so that we can obtain the distinguished name. loadUserByAccountName(aUserBag); // Now we will use the DN to find all of the groups the user is a member of. String distinguishedName = aUserBag.getValueAsString(LDAP_DISTINGUISHED_NAME); if (StringUtils.isEmpty(distinguishedName)) distinguishedName = getPropertyValue("user_searchbasedn", null); // Next, we will initialize our group membership table. DataTable memberTable = new DataTable(aUserBag); memberTable.setName(String.format("%s Group Membership", aUserBag.getValueAsString(LDAP_COMMON_NAME))); // The next logic section will query AD for all of the groups the user is a member // of. Because we are following tokenGroups, we will gain access to nested groups. String groupSearchBaseDN = getPropertyValue("group_searchbasedn", null); SearchControls userSearchControls = new SearchControls(); userSearchControls.setSearchScope(SearchControls.OBJECT_SCOPE); StringBuffer groupsSearchFilter = null; String ldapAttrNames[] = { "tokenGroups" }; userSearchControls.setReturningAttributes(ldapAttrNames); try { NamingEnumeration<?> userSearchResponse = mLdapContext.search(distinguishedName, "(objectClass=user)", userSearchControls); if ((userSearchResponse != null) && (userSearchResponse.hasMoreElements())) { groupsSearchFilter = new StringBuffer(); groupsSearchFilter.append("(|"); SearchResult userSearchResult = (SearchResult) userSearchResponse.next(); Attributes userResultAttributes = userSearchResult.getAttributes(); if (userResultAttributes != null) { try { for (NamingEnumeration<?> searchResultAttributesAll = userResultAttributes .getAll(); searchResultAttributesAll.hasMore();) { Attribute attr = (Attribute) searchResultAttributesAll.next(); for (NamingEnumeration<?> namingEnumeration = attr.getAll(); namingEnumeration .hasMore();) { objectSid = (byte[]) namingEnumeration.next(); groupsSearchFilter.append("(objectSid=" + objectSidToString2(objectSid) + ")"); } groupsSearchFilter.append(")"); } } catch (NamingException e) { String msgStr = String.format("LDAP Listing Member Exception: %s", e.getMessage()); appLogger.error(msgStr, e); throw new NSException(msgStr); } } userSearchResponse.close(); // Finally, we will query each group in the search filter and add it to the table. SearchControls groupSearchControls = new SearchControls(); groupSearchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); int field = 0; int attrCount = aGroupBag.count(); String[] groupsReturnedAtts = new String[attrCount]; for (DataField complexField : aGroupBag.getFields()) { fieldName = complexField.getName(); groupsReturnedAtts[field++] = fieldName; } groupSearchControls.setReturningAttributes(groupsReturnedAtts); NamingEnumeration<?> groupSearchResponse = mLdapContext.search(groupSearchBaseDN, groupsSearchFilter.toString(), groupSearchControls); while ((groupSearchResponse != null) && (groupSearchResponse.hasMoreElements())) { SearchResult groupSearchResult = (SearchResult) groupSearchResponse.next(); Attributes groupResultAttributes = groupSearchResult.getAttributes(); if (groupResultAttributes != null) { groupBag = new DataBag(aGroupBag); for (DataField complexField : groupBag.getFields()) { fieldName = complexField.getName(); responseAttribute = groupResultAttributes.get(fieldName); if (responseAttribute != null) { if (fieldName.equals(LDAP_OBJECT_SID)) { objectSid = (byte[]) responseAttribute.get(); fieldValue = objectSidToString2(objectSid); } else fieldValue = (String) responseAttribute.get(); if (StringUtils.isNotEmpty(fieldValue)) complexField.setValue(fieldValue); } } memberTable.addRow(groupBag); } } if (groupSearchResponse != null) groupSearchResponse.close(); } } catch (NamingException e) { String msgStr = String.format("LDAP Search Error (%s): %s", distinguishedName, e.getMessage()); appLogger.error(msgStr, e); throw new NSException(msgStr); } appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); return memberTable; }
From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java
@SuppressWarnings("unchecked") private SearchResult findUser(String username) throws NamingException, LoginException { SearchControls ctls = new SearchControls(); ctls.setCountLimit(1);/*from ww w. j a v a 2s.c o m*/ ctls.setDerefLinkFlag(true); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = OBJECT_CLASS_FILTER; debug("Searching for users with filter: \'" + filter + "\'" + " from base dn: " + _userBaseDn); Object[] filterArguments = new Object[] { _userObjectClass, _userIdAttribute, username }; NamingEnumeration results = _rootContext.search(_userBaseDn, filter, filterArguments, ctls); debug("Found user?: " + results.hasMoreElements()); if (!results.hasMoreElements()) { throw new LoginException("User not found."); } return (SearchResult) results.nextElement(); }
From source file:org.olat.ldap.LDAPLoginManagerImpl.java
private void searchInLdap(final LdapVisitor visitor, final String filter, final String[] returningAttrs, final LdapContext ctx) { final SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setReturningAttributes(returningAttrs); ctls.setCountLimit(0); // set no limits final boolean paging = isPagedResultControlSupported(ctx); for (final String ldapBase : LDAPLoginModule.getLdapBases()) { int counter = 0; try {/*from w w w. ja v a 2 s. co m*/ if (paging) { byte[] cookie = null; ctx.setRequestControls( new Control[] { new PagedResultsControl(PAGE_SIZE, Control.NONCRITICAL) }); do { final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls); while (enm.hasMore()) { visitor.visit(enm.next()); } cookie = getCookie(ctx); } while (cookie != null); } else { final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls); while (enm.hasMore()) { visitor.visit(enm.next()); } counter++; } } catch (final SizeLimitExceededException e) { logError("SizeLimitExceededException after " + counter + " records when getting all users from LDAP, reconfigure your LDAP server, hints: http://www.ldapbrowser.com/forum/viewtopic.php?t=14", null); } catch (final NamingException e) { logError("NamingException when trying to fetch deleted users from LDAP using ldapBase::" + ldapBase + " on row::" + counter, e); } catch (final Exception e) { logError("Exception when trying to fetch deleted users from LDAP using ldapBase::" + ldapBase + " on row::" + counter, e); } } }