List of usage examples for javax.naming.directory SearchControls SearchControls
public SearchControls()
From source file:org.apache.zeppelin.realm.ActiveDirectoryGroupRealm.java
private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException { Set<String> roleNames = new LinkedHashSet<>(); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String userPrincipalName = username; if (this.principalSuffix != null && userPrincipalName.indexOf('@') < 0) { userPrincipalName += principalSuffix; }//from ww w.j ava 2 s . c o m String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))"; Object[] searchArguments = new Object[] { userPrincipalName }; NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); if (log.isDebugEnabled()) { log.debug("Retrieving group names for user [" + sr.getName() + "]"); } Attributes attrs = sr.getAttributes(); if (attrs != null) { NamingEnumeration ae = attrs.getAll(); while (ae.hasMore()) { Attribute attr = (Attribute) ae.next(); if (attr.getID().equals("memberOf")) { Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr); if (log.isDebugEnabled()) { log.debug("Groups found for user [" + username + "]: " + groupNames); } Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames); roleNames.addAll(rolesForGroups); } } } } return roleNames; }
From source file:ru.efo.security.ADUserDetailsService.java
private ADUserDetails loadUserByUsername(DirContext context, String username, String password) throws UsernameNotFoundException { try {/*from ww w. jav a 2 s. c om*/ SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); // search for username NamingEnumeration<SearchResult> renum = context.search(userSearchBase, "(&(objectClass=user)(sAMAccountName={0}))", new Object[] { username }, controls); if (!renum.hasMoreElements()) { throw new UsernameNotFoundException("User '" + username + "' is not exist"); } SearchResult result = renum.next(); final Attributes attributes = result.getAttributes(); // User's display name String displayName = null; Attribute attr = attributes.get(displayNameAttribute); if (attr != null) { displayName = attr.get().toString(); } if (!StringUtils.hasText(displayName)) displayName = username; logger.log(Level.FINE, "Display name: " + displayName); // User's email String email = null; attr = attributes.get(emailAttribute); if (attr != null) { email = attr.get().toString(); } logger.log(Level.FINE, "E-mail: " + email); // User's phone number String phone = null; attr = attributes.get(phoneAttribute); if (attr != null) { phone = attr.get().toString(); } logger.log(Level.FINE, "Phone: " + phone); // Is user blocked boolean blocked = false; attr = attributes.get("userAccountControl"); if (attr != null) { blocked = (Long.parseLong(attr.get().toString()) & 2) != 0; } logger.log(Level.FINE, "Blocked: " + blocked); // describe roles and groups final Set<String> roles = new TreeSet<>(); final Set<String> groups = new TreeSet<>(); Attribute memberOf = attributes.get("memberOf"); describeRoles(context, memberOf, groups, roles); // Describe user primary role Attribute attrPrimaryGroupId = attributes.get("primaryGroupId"); Attribute attrObjectSid = attributes.get("objectSid"); if (attrPrimaryGroupId != null && attrObjectSid != null) { int primaryGroupId = Integer.parseInt(attrPrimaryGroupId.get().toString()); byte[] objectSid = (byte[]) attrObjectSid.get(); // add primary group RID for (int i = 0; i < 4; i++) { objectSid[objectSid.length - 4 + i] = (byte) (primaryGroupId & 0xFF); primaryGroupId >>= 8; } StringBuilder tmp = new StringBuilder(); for (int i = 2; i <= 7; i++) { tmp.append(Integer.toHexString(objectSid[i] & 0xFF)); } // convert objectSid to String StringBuilder sidBuilder = new StringBuilder("S-").append(objectSid[0]).append("-") .append(Long.parseLong(tmp.toString(), 16)); // the sub authorities count int count = objectSid[1]; // add authorities for (int i = 0; i < count; i++) { tmp.setLength(0); int offset = i * 4; tmp.append(String.format("%02X%02X%02X%02X", (objectSid[11 + offset] & 0xFF), (objectSid[10 + offset] & 0xFF), (objectSid[9 + offset] & 0xFF), (objectSid[8 + offset] & 0xFF))); sidBuilder.append('-').append(Long.parseLong(tmp.toString(), 16)); } SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); renum = context.search(userSearchBase, "(&(objectClass=group)(objectSid={0}))", new Object[] { sidBuilder.toString() }, searchControls); if (renum.hasMoreElements()) { result = renum.next(); attr = result.getAttributes().get("distinguishedName"); describeRoles(context, attr, groups, roles); } } return new ADUserDetails(username, password, displayName, email, phone, blocked, groups, roles); } catch (NamingException ex) { logger.log(Level.SEVERE, "Could not find user '" + username + "'", ex); throw new UsernameNotFoundException(ex.getMessage()); } }
From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java
/** * *///from w w w. j av a 2s . co m public void doUpdateCredential(String userName, Object newCredential, Object oldCredential) throws UserStoreException { if (!isSSLConnection) { logger.warn("Unsecured connection is being used. Password operations will fail"); } DirContext dirContext = this.connectionSource.getContext(); String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userListFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER); String userNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE); // String searchFilter = // realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); String searchFilter = "(&" + userListFilter + "(" + userNameAttribute + "=" + escapeSpecialCharactersForFilter(userName) + "))"; SearchControls searchControl = new SearchControls(); String[] returningAttributes = { "CN" }; searchControl.setReturningAttributes(returningAttributes); searchControl.setSearchScope(SearchControls.SUBTREE_SCOPE); DirContext subDirContext = null; NamingEnumeration<SearchResult> searchResults = null; try { // search the user with UserNameAttribute and obtain its CN attribute searchResults = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControl); SearchResult user = null; int count = 0; while (searchResults.hasMore()) { if (count > 0) { throw new UserStoreException( "There are more than one result in the user store " + "for user: " + userName); } user = searchResults.next(); count++; } String userCNValue = null; if (user.getAttributes() != null) { Attribute cnAttribute = user.getAttributes().get("CN"); if (cnAttribute != null) { userCNValue = (String) cnAttribute.get(); } else { throw new UserStoreException("Can not update credential: CN attribute is null"); } } ModificationItem[] mods = null; // The user tries to change his own password if (oldCredential != null && newCredential != null) { mods = new ModificationItem[1]; /* * byte[] oldUnicodePassword = createUnicodePassword((String) oldCredential); byte[] * newUnicodePassword = createUnicodePassword((String) newCredential); */ mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE, createUnicodePassword((String) newCredential))); /* * mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute( * LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE, newUnicodePassword)); */ } subDirContext = (DirContext) dirContext.lookup(searchBase); subDirContext.modifyAttributes("CN" + "=" + escapeSpecialCharactersForDN(userCNValue), mods); } catch (NamingException e) { String error = "Can not access the directory service for user : " + userName; if (logger.isDebugEnabled()) { logger.debug(error, e); } throw new UserStoreException(error, e); } finally { JNDIUtil.closeNamingEnumeration(searchResults); JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(dirContext); } }
From source file:com.alfaariss.oa.engine.attribute.gather.processor.jndi.JNDIGatherer.java
/** * Gathers attributes from JNDI storage to the supplied attributes object. * @see com.alfaariss.oa.engine.core.attribute.gather.processor.IProcessor#process(java.lang.String, com.alfaariss.oa.api.attribute.IAttributes) *//*ww w .jav a 2 s . com*/ public void process(String sUserId, IAttributes oAttributes) throws AttributeException { 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 AttributeException(SystemErrors.ERROR_RESOURCE_CONNECT, e); } SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); if (_listGather.size() > 0) { String[] saAttributes = _listGather.toArray(new String[0]); oScope.setReturningAttributes(saAttributes); } String searchFilter = resolveSearchQuery(sUserId); 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 for id: "); sbFailed.append(sUserId); _logger.error(sbFailed.toString(), e); throw new AttributeException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } catch (NamingException e) { _logger.debug("User unknown: " + sUserId); return; } if (oNamingEnumeration.hasMore()) { SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next(); Attributes oSearchedAttributes = oSearchResult.getAttributes(); NamingEnumeration neAttributes = oSearchedAttributes.getAll(); while (neAttributes.hasMore()) { Attribute oAttribute = (Attribute) neAttributes.next(); String sAttributeName = oAttribute.getID(); String sMappedName = _htMapper.get(sAttributeName); if (sMappedName != null) sAttributeName = sMappedName; if (oAttribute.size() > 1) { Vector<Object> vValue = new Vector<Object>(); NamingEnumeration neAttribute = oAttribute.getAll(); while (neAttribute.hasMore()) vValue.add(neAttribute.next()); oAttributes.put(sAttributeName, vValue); } else { Object oValue = oAttribute.get(); if (oValue == null) oValue = ""; oAttributes.put(sAttributeName, oValue); } } } } catch (AttributeException e) { throw e; } catch (NamingException e) { _logger.debug("Failed to fetch attributes for user: " + sUserId, e); } catch (Exception e) { _logger.fatal("Could not retrieve fields for user with id: " + sUserId, e); throw new AttributeException(SystemErrors.ERROR_INTERNAL); } finally { if (oNamingEnumeration != null) { try { oNamingEnumeration.close(); } catch (Exception e) { _logger.error("Could not close Naming Enumeration after searching for user with id: " + sUserId, e); } } if (oDirContext != null) { try { oDirContext.close(); } catch (NamingException e) { _logger.error("Could not close Dir Context after searching for user with id: " + sUserId, e); } } } }
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</code>, and extracting the <code>uid</code> token of the * <code>uniqueMember</code> attribute. *//*from ww w .jav a 2s . c om*/ @Test public void testGetAllUserNames1() throws Exception { 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(); Transformer transformer1 = new SearchResultToAttrValueList("uniqueMember", "uid"); //$NON-NLS-1$ //$NON-NLS-2$ GenericLdapSearch allUsernamesSearch = new GenericLdapSearch(getContextSource(), paramFactory, transformer1); allUsernamesSearch.afterPropertiesSet(); DefaultLdapUserRoleListService userRoleListService = getDefaultLdapUserRoleListService(); userRoleListService.setAllUsernamesSearch(allUsernamesSearch); List res = userRoleListService.getAllUsers(); 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$ } }
From source file:org.apache.directory.server.operations.bind.MiscBindIT.java
/** * Reproduces the problem with/*w ww . j a v a 2 s . c o m*/ * <a href="http://issues.apache.org/jira/browse/DIREVE-239">DIREVE-239</a>. * * @throws Exception if anything goes wrong */ @Test public void testAdminAccessBug() throws Exception { getLdapServer().getDirectoryService().setAllowAnonymousAccess(true); // Use the SUN JNDI provider to hit server port and bind as anonymous final Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort())); env.put("java.naming.ldap.version", "3"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); Attributes attributes = new BasicAttributes(true); Attribute objectClass = new BasicAttribute("objectClass"); objectClass.add("top"); objectClass.add("organizationalUnit"); attributes.put(objectClass); attributes.put("ou", "blah"); InitialDirContext ctx = new InitialDirContext(env); ctx.createSubcontext("ou=blah,ou=system", attributes); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.OBJECT_SCOPE); controls.setReturningAttributes(new String[] { "+" }); NamingEnumeration<SearchResult> list = ctx.search("ou=blah,ou=system", "(objectClass=*)", controls); SearchResult result = list.next(); list.close(); Attribute creatorsName = result.getAttributes().get("creatorsName"); assertEquals("", creatorsName.get()); ctx.destroySubcontext("ou=blah,ou=system"); }
From source file:org.apache.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java
protected boolean authenticate(String username) throws Exception { DirContext context = open();/* w ww.j a v a 2 s. c o m*/ try { String filter = userSearchMatchingFormat.format(new String[] { username }); SearchControls constraints = new SearchControls(); if (userSearchSubtreeBool) { constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); } else { constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE); } // setup attributes String[] attribs; if (userRoleName == null) { attribs = new String[] {}; } else { attribs = new String[] { userRoleName }; } constraints.setReturningAttributes(attribs); NamingEnumeration results = context.search(userBase, filter, constraints); if (results == null || !results.hasMore()) { log.error("No roles associated with user " + username); loginSucceeded = false; throw new FailedLoginException(); } SearchResult result = (SearchResult) results.next(); if (results.hasMore()) { // ignore for now } NameParser parser = context.getNameParser(""); Name contextName = parser.parse(context.getNameInNamespace()); Name baseName = parser.parse(userBase); Name entryName = parser.parse(result.getName()); Name name = contextName.addAll(baseName); name = name.addAll(entryName); String dn = name.toString(); Attributes attrs = result.getAttributes(); if (attrs == null) { return false; } ArrayList<String> roles = null; if (userRoleName != null) { roles = addAttributeValues(userRoleName, attrs, roles); } // check the credentials by binding to server // bindUser(context, dn); // if authenticated add more roles roles = getRoles(context, dn, username, roles); for (String role : roles) { groups.add(role); } if (groups.isEmpty()) { log.error("No roles associated with user " + username); loginSucceeded = false; throw new FailedLoginException(); } else loginSucceeded = true; } catch (CommunicationException e) { close(context); throw (LoginException) new FailedLoginException().initCause(e); } catch (NamingException e) { close(context); throw (LoginException) new FailedLoginException().initCause(e); } return true; }
From source file:org.apache.cloudstack.ldap.OpenLdapUserManagerImpl.java
@Override public List<LdapUser> searchUsers(final String username, final LdapContext context) throws NamingException, IOException { final SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(_ldapConfiguration.getScope()); searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes()); String basedn = _ldapConfiguration.getBaseDn(); if (StringUtils.isBlank(basedn)) { throw new IllegalArgumentException("ldap basedn is not configured"); }//w w w .j av a2 s. com byte[] cookie = null; int pageSize = _ldapConfiguration.getLdapPageSize(); context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); final List<LdapUser> users = new ArrayList<LdapUser>(); NamingEnumeration<SearchResult> results; do { results = context.search(basedn, generateSearchFilter(username), searchControls); while (results.hasMoreElements()) { final SearchResult result = results.nextElement(); if (!isUserDisabled(result)) { users.add(createUser(result)); } } Control[] contextControls = context.getResponseControls(); if (contextControls != null) { for (Control control : contextControls) { if (control instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) control; cookie = prrc.getCookie(); } } } else { s_logger.info("No controls were sent from the ldap server"); } context.setRequestControls( new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); } while (cookie != null); return users; }
From source file:org.nuxeo.ecm.directory.ldap.LDAPDirectory.java
public SearchControls getSearchControls(boolean fetchAllAttributes) { if (fetchAllAttributes) { // return the precomputed scts instance return searchControls; } else {/*from w w w. ja va2 s .c o m*/ // build a new ftcs instance with no attribute filtering LDAPDirectoryDescriptor ldapDirectoryDesc = getDescriptor(); SearchControls scts = new SearchControls(); scts.setSearchScope(ldapDirectoryDesc.getSearchScope()); scts.setReturningAttributes(new String[] { ldapDirectoryDesc.rdnAttribute, ldapDirectoryDesc.fieldMapping.get(getIdField()) }); return scts; } }
From source file:org.pegadi.server.user.LDAPUserServerImpl.java
/** * Returns an array of users./*from www . j a va2 s. c om*/ * * @param inactive <code>true</code> if inactive users should be included. * @return an array of <code>User</code>s. */ public List<Person> getAllUsers(boolean inactive) { ArrayList<Person> users = new ArrayList<Person>(); try { SearchControls sc = new SearchControls(); String[] getThese = { "sn", "gn", "mail", "uid", "employeeNumber" }; sc.setReturningAttributes(getThese); if (inactive) { Attributes attrs = ctx.getAttributes("ou=people", getThese); users.add(this.createUser(attrs)); } else { NamingEnumeration e = ctx.search("ou=people", "(active=1)", sc); while (e.hasMore()) { SearchResult sr = (SearchResult) e.next(); users.add(this.createUser(sr.getAttributes())); } } Collections.sort(users); return users; } catch (NamingException er) { log.error("Could not get users", er); } catch (Exception e) { log.error("Something else", e); } return null; }