List of usage examples for javax.naming.directory SearchControls SearchControls
public SearchControls()
From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java
public List<String> getGroups(String username, DirContext context) throws MappingException { List<String> userGroups = new ArrayList<String>(); NamingEnumeration<SearchResult> namingEnumeration = null; try {//from ww w. j a v a2s. co m SearchControls searchControls = new SearchControls(); searchControls.setDerefLinkFlag(true); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String groupEntry = null; try { //try to look the user up User user = userManager.findUser(username); if (user instanceof LdapUser) { LdapUser ldapUser = LdapUser.class.cast(user); Attribute dnAttribute = ldapUser.getOriginalAttributes().get(getLdapDnAttribute()); if (dnAttribute != null) { groupEntry = String.class.cast(dnAttribute.get()); } } } catch (UserNotFoundException e) { log.warn("Failed to look up user {}. Computing distinguished name manually", username, e); } catch (UserManagerException e) { log.warn("Failed to look up user {}. Computing distinguished name manually", username, e); } if (groupEntry == null) { //failed to look up the user's groupEntry directly StringBuilder builder = new StringBuilder(); String posixGroup = "posixGroup"; if (posixGroup.equals(getLdapGroupClass())) { builder.append(username); } else { builder.append(this.userIdAttribute).append("=").append(username).append(",") .append(getBaseDn()); } groupEntry = builder.toString(); } String filter = new StringBuilder().append("(&").append("(objectClass=" + getLdapGroupClass() + ")") .append("(").append(getLdapGroupMember()).append("=").append(Rdn.escapeValue(groupEntry)) .append(")").append(")").toString(); log.debug("filter: {}", filter); namingEnumeration = context.search(getGroupsDn(), filter, searchControls); while (namingEnumeration.hasMore()) { SearchResult searchResult = namingEnumeration.next(); List<String> allMembers = new ArrayList<String>(); Attribute uniqueMemberAttr = searchResult.getAttributes().get(getLdapGroupMember()); if (uniqueMemberAttr != null) { NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr .getAll(); while (allMembersEnum.hasMore()) { String userName = allMembersEnum.next(); //the original dn allMembers.add(userName); // uid=blabla we only want bla bla userName = StringUtils.substringAfter(userName, "="); userName = StringUtils.substringBefore(userName, ","); allMembers.add(userName); } close(allMembersEnum); } if (allMembers.contains(username)) { String groupName = searchResult.getName(); // cn=blabla we only want bla bla groupName = StringUtils.substringAfter(groupName, "="); userGroups.add(groupName); } else if (allMembers.contains(groupEntry)) { String groupName = searchResult.getName(); // cn=blabla we only want bla bla groupName = StringUtils.substringAfter(groupName, "="); userGroups.add(groupName); } } return userGroups; } catch (LdapException e) { throw new MappingException(e.getMessage(), e); } catch (NamingException e) { throw new MappingException(e.getMessage(), e); } finally { close(namingEnumeration); } }
From source file:org.apache.directory.server.tools.commands.exportcmd.ExportCommandExecutor.java
/** * Gets and returns the entries from the server. * /* w w w . j a va 2 s . c o m*/ * @throws ToolCommandException * @throws NamingException */ public NamingEnumeration connectToServerAndGetEntries() throws ToolCommandException { // Connecting to the LDAP Server if (isDebugEnabled()) { notifyOutputListener("Connecting to LDAP server"); notifyOutputListener("Host: " + host); notifyOutputListener("Port: " + port); notifyOutputListener("User DN: " + user); notifyOutputListener("Base DN: " + baseDN); notifyOutputListener("Authentication: " + auth); } Hashtable env = new Hashtable(); env.put(Context.SECURITY_PRINCIPAL, user); env.put(Context.SECURITY_CREDENTIALS, password); env.put(Context.SECURITY_AUTHENTICATION, auth); env.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port + "/" + baseDN); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); DirContext ctx; try { ctx = new InitialDirContext(env); } catch (NamingException e) { throw new ToolCommandException("Could not connect to the server.\nError: " + e.getMessage()); } // Setting up search scope SearchControls ctls = new SearchControls(); ctls.setSearchScope(scope); // Fetching entries try { return ctx.search(exportPoint, "(objectClass=*)", ctls); } catch (NamingException e) { throw new ToolCommandException("Could not retreive entries"); } }
From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java
private boolean bindSearchX(String username, String password, Hashtable<String, String> env, boolean bind) throws AuthenticationException, NamingException { env.put(Context.SECURITY_PRINCIPAL, ldapSecurityPrincipal); env.put(Context.SECURITY_CREDENTIALS, ldapSecurityCredentials); DirContext ctx = null;/*from w w w . j a v a 2s. c o m*/ try { ctx = new InitialDirContext(env); } catch (NamingException ne) { log.error("Failed to bind as: {}", ldapSecurityPrincipal); } // ensure we have the userPassword attribute at a minimum String[] attributeList = new String[] { "userPassword" }; SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(attributeList); sc.setDerefLinkFlag(true); sc.setReturningObjFlag(false); sc.setTimeLimit(5000); String filter = "(" + filterPrefix + idAttr + "=" + username + filterSuffix + ")"; // Do the search NamingEnumeration<SearchResult> results = ctx.search(baseDn, filter, sc); if (!results.hasMore()) { log.warn("no valid user found."); return false; } SearchResult result = results.next(); log.debug("authenticating user: {}", result.getNameInNamespace()); if (bind) { // setup user context for binding Hashtable<String, String> userEnv = new Hashtable<String, String>(); userEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); userEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); userEnv.put(Context.PROVIDER_URL, baseUrl); userEnv.put(Context.SECURITY_PRINCIPAL, result.getNameInNamespace()); userEnv.put(Context.SECURITY_CREDENTIALS, password); try { new InitialDirContext(userEnv); } catch (NamingException ne) { log.error("failed to authenticate user: " + result.getNameInNamespace()); throw ne; } } else { // get userPassword attribute Attribute up = result.getAttributes().get("userPassword"); if (up == null) { log.error("unable to read userPassword attribute for: {}", result.getNameInNamespace()); return false; } byte[] userPasswordBytes = (byte[]) up.get(); String userPassword = new String(userPasswordBytes); // compare passwords - also handles encodings if (!passwordsMatch(password, userPassword)) { return false; } } return true; }
From source file:org.jasig.schedassist.impl.ldap.LDAPDelegateCalendarAccountDaoImpl.java
/** * //from ww w .j ava 2 s . c o m * @param searchFilter * @param owner * @return */ @SuppressWarnings("unchecked") protected List<IDelegateCalendarAccount> executeSearchReturnList(final Filter searchFilter, final ICalendarAccount owner) { SearchControls searchControls = new SearchControls(); searchControls.setCountLimit(searchResultsLimit); searchControls.setTimeLimit(searchTimeLimit); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); List<IDelegateCalendarAccount> results = Collections.emptyList(); try { results = ldapTemplate.search(baseDn, searchFilter.toString(), searchControls, new DefaultDelegateAccountAttributesMapperImpl(ldapAttributesKey, owner)); if (log.isDebugEnabled()) { log.debug("search " + searchFilter + " returned " + results.size() + " results"); } if (isTreatOwnerAttributeAsDistinguishedName() && owner != null && owner instanceof HasDistinguishedName) { HasDistinguishedName ldapOwnerAccount = (HasDistinguishedName) owner; enforceDistinguishedNameMatch(results, ldapOwnerAccount); } Collections.sort(results, new DelegateDisplayNameComparator()); } catch (SizeLimitExceededException e) { log.debug("search filter exceeded size limit (" + searchResultsLimit + "): " + searchFilter); } catch (TimeLimitExceededException e) { log.debug("search filter exceeded time limit(" + searchTimeLimit + " milliseconds): " + searchFilter); } return results; }
From source file:org.infoscoop.account.ldap.LDAPAccountManager.java
private void setGroup(DirContext context, LDAPAccount user) throws NamingException { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); //create the filter of group Map filters = new HashMap(); String uniqueMemberAttrName = "uniquemember"; if (this.propAttrMap.containsKey("org_member")) uniqueMemberAttrName = (String) this.propAttrMap.get("org_member"); filters.put(uniqueMemberAttrName, user.getDn()); String grpFilter = buildGroupFilterByDN(filters); NamingEnumeration grpRes = context.search(groupBase, grpFilter, searchControls); List grpList = new ArrayList(); while (grpRes.hasMoreElements()) { SearchResult findGrpEntry = (SearchResult) grpRes.next(); if (log.isDebugEnabled()) log.debug("Found Groups: " + findGrpEntry.getAttributes().toString()); String grpdn = findGrpEntry.getName() + "," + groupBase; grpList.add(createLDAPGroup(grpdn, findGrpEntry.getAttributes())); }/* www. ja v a 2 s . c om*/ IGroup[] igroup = new IGroup[grpList.size()]; for (int i = 0; i < igroup.length; i++) { igroup[i] = (IGroup) grpList.get(i); } user.setGroups(igroup); }
From source file:org.pentaho.test.platform.plugin.services.security.userrole.ldap.DefaultLdapUserRoleListServiceTests.java
@Test public void testGetAllUserNames1ForTenant() throws Exception { ITenant defaultTenant = new Tenant("/pentaho/tenant0", true); login("suzy", defaultTenant); SearchControls con1 = new SearchControls(); con1.setReturningAttributes(new String[] { "uniqueMember" }); //$NON-NLS-1$ LdapSearchParamsFactoryImpl paramFactory = new LdapSearchParamsFactoryImpl("ou=groups", //$NON-NLS-1$ "(objectClass=groupOfUniqueNames)", con1); //$NON-NLS-1$ paramFactory.afterPropertiesSet();// w w w .j ava2s .c o m Transformer transformer1 = new SearchResultToAttrValueList("uniqueMember", "uid"); //$NON-NLS-1$ //$NON-NLS-2$ GenericLdapSearch allUsernamesSearch = new GenericLdapSearch(getContextSource(), paramFactory, transformer1); allUsernamesSearch.afterPropertiesSet(); DefaultLdapUserRoleListService userRoleListService = new DefaultLdapUserRoleListService(); userRoleListService.setAllUsernamesSearch(allUsernamesSearch); List res = userRoleListService.getAllUsers(defaultTenant); assertTrue(res.contains("pat")); //$NON-NLS-1$ assertTrue(res.contains("admin")); //$NON-NLS-1$ if (logger.isDebugEnabled()) { logger.debug("results of getAllUserNames1(): " + res); //$NON-NLS-1$ } try { userRoleListService.getAllUsers(new Tenant("/pentaho", true)); } catch (UnsupportedOperationException uoe) { assertNotNull(uoe); } }
From source file:org.wso2.carbon.appfactory.userstore.AppFactoryTenantManager.java
protected NamingEnumeration searchForObject(String searchFilter, String returnedAtts[], DirContext dirContext, String searchBase) throws UserStoreException { SearchControls searchCtls;/*from www.j av a 2 s .c o m*/ searchCtls = new SearchControls(); searchCtls.setSearchScope(2); if (returnedAtts != null && returnedAtts.length > 0) searchCtls.setReturningAttributes(returnedAtts); try { return dirContext.search(searchBase, searchFilter, searchCtls); } catch (NamingException e) { log.error("Search failed.", e); throw new UserStoreException(e.getMessage()); } }
From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java
/** * Returns the values of the specified fields for the supplied id. * @see IExternalStorage#getFields(java.lang.String, java.util.List) *//*from w w w . j a v a 2 s .c om*/ public Hashtable<String, Object> getFields(String id, List<String> fields) throws UserException { Hashtable<String, Object> htReturn = new Hashtable<String, Object>(); DirContext oDirContext = null; NamingEnumeration oNamingEnumeration = null; try { try { oDirContext = new InitialDirContext(_htJNDIEnvironment); } catch (NamingException e) { _logger.error("Could not create the connection: " + _htJNDIEnvironment); throw new UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e); } SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); String[] saFields = fields.toArray(new String[0]); oScope.setReturningAttributes(saFields); String searchFilter = resolveSearchQuery(id); try { oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope); } catch (InvalidSearchFilterException e) { StringBuffer sbFailed = new StringBuffer("Wrong filter: "); sbFailed.append(searchFilter); sbFailed.append(" while searching for attributes '"); sbFailed.append(fields); sbFailed.append("' for id: "); sbFailed.append(id); _logger.error(sbFailed.toString(), e); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } catch (NamingException e) { _logger.error("User unknown: " + id); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } if (!oNamingEnumeration.hasMore()) { StringBuffer sbFailed = new StringBuffer("User with id '"); sbFailed.append(id); sbFailed.append("' not found after LDAP search with filter: "); sbFailed.append(searchFilter); _logger.error(sbFailed.toString()); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next(); Attributes oAttributes = oSearchResult.getAttributes(); NamingEnumeration neAttributes = oAttributes.getAll(); while (neAttributes.hasMore()) { Attribute oAttribute = (Attribute) neAttributes.next(); String sAttributeName = oAttribute.getID(); if (oAttribute.size() > 1) { Vector<Object> vValue = new Vector<Object>(); NamingEnumeration neAttribute = oAttribute.getAll(); while (neAttribute.hasMore()) vValue.add(neAttribute.next()); htReturn.put(sAttributeName, vValue); } else { Object oValue = oAttribute.get(); if (oValue == null) oValue = ""; htReturn.put(sAttributeName, oValue); } } } catch (UserException e) { throw e; } catch (Exception e) { _logger.fatal("Could not retrieve fields: " + fields, e); throw new UserException(SystemErrors.ERROR_INTERNAL, e); } finally { if (oNamingEnumeration != null) { try { oNamingEnumeration.close(); } catch (Exception e) { _logger.error("Could not close Naming Enumeration after searching for user with id: " + id, e); } } if (oDirContext != null) { try { oDirContext.close(); } catch (NamingException e) { _logger.error("Could not close Dir Context after searching for user with id: " + id, e); } } } return htReturn; }
From source file:com.alfaariss.oa.authentication.password.jndi.JNDIProtocolResource.java
private boolean doBind(String sUserID, String sPassword) throws OAException, UserException { StringBuffer sbTemp = null;/*ww w .j av a2 s . co m*/ DirContext oDirContext = null; String sQuery = null; String sRelUserDn = null; boolean bResult = false; NamingEnumeration enumSearchResults = null; Hashtable<String, String> htEnvironment = new Hashtable<String, String>(); htEnvironment.put(Context.PROVIDER_URL, _sJNDIUrl); htEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, _sDriver); htEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple"); if (_bSSL) { htEnvironment.put(Context.SECURITY_PROTOCOL, "ssl"); } if (_sPrincipalDn.length() <= 0) // If no principal dn is known, we do a simple binding { String sEscUserID = JNDIUtil.escapeDN(sUserID); _logger.debug("Escaped user: " + sEscUserID); sbTemp = new StringBuffer(_sUserDn); sbTemp.append('='); sbTemp.append(sEscUserID); sbTemp.append(", "); sbTemp.append(_sBaseDn); htEnvironment.put(Context.SECURITY_PRINCIPAL, sbTemp.toString()); htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword); try { oDirContext = new InitialDirContext(htEnvironment); bResult = true; } catch (AuthenticationException e) { // If supplied credentials are invalid or when authentication fails // while accessing the directory or naming service. _logger.debug("Could not authenticate user (invalid password): " + sUserID, e); } catch (CommunicationException eC) { // If communication with the directory or naming service fails. _logger.warn("A communication error has occured", eC); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } catch (NamingException eN) { // The initial dir context could not be created. _logger.warn("A naming error has occured", eN); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } finally { try { if (oDirContext != null) { oDirContext.close(); } } catch (Exception e) { _logger.warn("Could not close connection with '" + _sJNDIUrl + '\'', e); } } } else //search through the subtree { // 1 - Try to bind to LDAP using the security principal's DN and its password htEnvironment.put(Context.SECURITY_PRINCIPAL, _sPrincipalDn); htEnvironment.put(Context.SECURITY_CREDENTIALS, _sPrincipalPwd); try { oDirContext = new InitialDirContext(htEnvironment); } catch (AuthenticationException eA) { _logger.warn("Could not bind to LDAP server", eA); throw new OAException(SystemErrors.ERROR_RESOURCE_CONNECT); } catch (CommunicationException eC) { _logger.warn("A communication error has occured", eC); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } catch (NamingException eN) { _logger.warn("A naming error has occured", eN); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } // 2 - Search through the context for user's DN relative to the base DN sQuery = resolveSearchQuery(sUserID); SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); try { enumSearchResults = oDirContext.search(_sBaseDn, sQuery, oScope); } catch (NamingException eN) { _logger.warn("User id not found in password backend for user: " + sUserID, eN); throw new UserException(UserEvent.AUTHN_METHOD_NOT_SUPPORTED); } finally { try { oDirContext.close(); oDirContext = null; } catch (Exception e) { _logger.warn("Could not close connection with '" + _sJNDIUrl + "'", e); } } try { if (!enumSearchResults.hasMoreElements()) { StringBuffer sb = new StringBuffer("User '"); sb.append(sUserID); sb.append("' not found during LDAP search. The filter was: '"); sb.append(sQuery); sb.append("'"); _logger.warn(sb.toString()); throw new UserException(UserEvent.AUTHN_METHOD_NOT_SUPPORTED); } SearchResult searchResult = (SearchResult) enumSearchResults.next(); sRelUserDn = searchResult.getName(); if (sRelUserDn == null) { _logger.warn("no user dn was returned for '" + sUserID + "'."); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } } catch (NamingException eN) { _logger.warn("failed to fetch profile of user '" + sUserID + "'.", eN); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } // 3 - Bind user using supplied credentials sbTemp = new StringBuffer(sRelUserDn); sbTemp.append(","); sbTemp.append(_sBaseDn); htEnvironment.put(Context.SECURITY_PRINCIPAL, sbTemp.toString()); htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword); try { oDirContext = new InitialDirContext(htEnvironment); bResult = true; } catch (AuthenticationException e) { _logger.debug("Could not authenticate user (invalid password): " + sUserID, e); } catch (CommunicationException eC) { _logger.warn("A communication error has occured", eC); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } catch (NamingException eN) { _logger.warn("A naming error has occured", eN); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } finally { try { if (oDirContext != null) { oDirContext.close(); } } catch (Exception e) { _logger.warn("Could not close connection with '" + _sJNDIUrl + "'.", e); } } } return bResult; }
From source file:iplatform.admin.ui.server.auth.ad.ActiveDirectoryLdapAuthenticationProvider.java
@SuppressWarnings("deprecation") private DirContextOperations searchForUser(DirContext ctx, String username) throws NamingException { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchFilter = "(&(objectClass=user)(userPrincipalName={0}))"; final String bindPrincipal = createBindPrincipal(username); String searchRoot = rootDn != null ? rootDn : searchRootFromPrincipal(bindPrincipal); try {/*from w ww . j av a 2 s. c om*/ return SpringSecurityLdapTemplate.searchForSingleEntryInternal(ctx, searchCtls, searchRoot, searchFilter, new Object[] { bindPrincipal }); } catch (IncorrectResultSizeDataAccessException incorrectResults) { if (incorrectResults.getActualSize() == 0) { UsernameNotFoundException userNameNotFoundException = new UsernameNotFoundException( "User " + username + " not found in directory.", username); userNameNotFoundException.initCause(incorrectResults); throw badCredentials(userNameNotFoundException); } // Search should never return multiple results if properly configured, so just rethrow throw incorrectResults; } }