List of usage examples for javax.naming.directory SearchControls SearchControls
public SearchControls()
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 . ja va2 s .c o 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: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.pentaho.test.platform.plugin.services.security.userrole.ldap.DefaultLdapUserRoleListServiceTests.java
/** * Search for all roles (aka authorities) starting at <code>ou=roles</code>, looking for objects with * <code>objectClass=organizationalRole</code>, and returning the <code>cn</code> attribute. *///from w w w .ja va 2 s . c om @Test public void testGetAllAuthorities1() { SearchControls con1 = new SearchControls(); con1.setReturningAttributes(new String[] { "cn" }); //$NON-NLS-1$ LdapSearchParamsFactory paramsFactory = new LdapSearchParamsFactoryImpl("ou=roles", //$NON-NLS-1$ "(objectClass=organizationalRole)", con1); //$NON-NLS-1$ Transformer one = new SearchResultToAttrValueList("cn"); //$NON-NLS-1$ Transformer two = new StringToGrantedAuthority(); Transformer[] transformers = { one, two }; Transformer transformer = new ChainedTransformer(transformers); LdapSearch rolesSearch = new GenericLdapSearch(getContextSource(), paramsFactory, transformer); DefaultLdapUserRoleListService userRoleListService = new DefaultLdapUserRoleListService(); userRoleListService.setAllAuthoritiesSearch(rolesSearch); List res = userRoleListService.getAllRoles(); assertTrue(res.contains("ROLE_CTO")); //$NON-NLS-1$ assertTrue(res.contains("ROLE_CEO")); //$NON-NLS-1$ if (logger.isDebugEnabled()) { logger.debug("results of getAllAuthorities1(): " + res); //$NON-NLS-1$ } }
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 ww.j a v a 2 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:org.pentaho.test.platform.plugin.services.security.userrole.ldap.DefaultLdapUserRoleListServiceTest.java
/** * Search for all roles (aka authorities) starting at <code>ou=roles</code>, looking for objects with * <code>objectClass=organizationalRole</code>, and returning the <code>cn</code> attribute. *//*from ww w. j a v a2s .c o m*/ @Test public void testGetAllAuthorities1() { SearchControls con1 = new SearchControls(); con1.setReturningAttributes(new String[] { "cn" }); //$NON-NLS-1$ LdapSearchParamsFactory paramsFactory = new LdapSearchParamsFactoryImpl("ou=roles", //$NON-NLS-1$ "(objectClass=organizationalRole)", con1); //$NON-NLS-1$ Transformer one = new SearchResultToAttrValueList("cn"); //$NON-NLS-1$ Transformer two = new StringToGrantedAuthority(); Transformer[] transformers = { one, two }; Transformer transformer = new ChainedTransformer(transformers); LdapSearch rolesSearch = new GenericLdapSearch(getContextSource(), paramsFactory, transformer); DefaultLdapUserRoleListService userRoleListService = getDefaultLdapUserRoleListService(); userRoleListService.setAllAuthoritiesSearch(rolesSearch); List res = userRoleListService.getAllRoles(); assertTrue(res.contains("ROLE_CTO")); //$NON-NLS-1$ assertTrue(res.contains("ROLE_CEO")); //$NON-NLS-1$ if (logger.isDebugEnabled()) { logger.debug("results of getAllAuthorities1(): " + res); //$NON-NLS-1$ } }
From source file:org.lsc.jndi.JndiServices.java
public SearchResult readEntry(final String base, final String filter, final boolean allowError) throws NamingException { SearchControls sc = new SearchControls(); return readEntry(base, filter, allowError, sc); }
From source file:org.wso2.carbon.identity.agent.userstore.manager.ldap.LDAPUserStoreManager.java
/** * {@inheritDoc}/*w w w .j av 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}//from w w w . j a va2 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) {/*from w w w . j a v a 2 s.c om*/ 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:org.pentaho.test.platform.plugin.services.security.userrole.ldap.DefaultLdapUserRoleListServiceTests.java
@Test public void testGetAllAuthorities1ForTenant() { ITenant defaultTenant = new Tenant("/pentaho/tenant0", true); login("suzy", defaultTenant); SearchControls con1 = new SearchControls(); con1.setReturningAttributes(new String[] { "cn" }); //$NON-NLS-1$ LdapSearchParamsFactory paramsFactory = new LdapSearchParamsFactoryImpl("ou=roles", //$NON-NLS-1$ "(objectClass=organizationalRole)", con1); //$NON-NLS-1$ Transformer one = new SearchResultToAttrValueList("cn"); //$NON-NLS-1$ Transformer two = new StringToGrantedAuthority(); Transformer[] transformers = { one, two }; Transformer transformer = new ChainedTransformer(transformers); LdapSearch rolesSearch = new GenericLdapSearch(getContextSource(), paramsFactory, transformer); DefaultLdapUserRoleListService userRoleListService = new DefaultLdapUserRoleListService(); userRoleListService.setAllAuthoritiesSearch(rolesSearch); List res = userRoleListService.getAllRoles(defaultTenant); assertTrue(res.contains("ROLE_CTO")); //$NON-NLS-1$ assertTrue(res.contains("ROLE_CEO")); //$NON-NLS-1$ if (logger.isDebugEnabled()) { logger.debug("results of getAllAuthorities1(): " + res); //$NON-NLS-1$ }/* w w w . j a v a 2s .c o m*/ try { userRoleListService.getAllRoles(new Tenant("/pentaho", true)); } catch (UnsupportedOperationException uoe) { assertNotNull(uoe); } }