List of usage examples for javax.naming.directory SearchResult getAttributes
public Attributes getAttributes()
From source file:org.apache.directory.server.operations.bind.MiscBindIT.java
/** * Reproduces the problem with//from w ww .ja v a 2s .co 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:com.konakart.bl.LDAPMgrCore.java
/** * Called if the LDAP module is installed and active. This method should return: * <ul>// www .j a v a2 s . co m * <li>A negative number in order for the login attempt to fail. The KonaKart login() method * will return a null sessionId</li> * <li>Zero to signal that this method is not implemented. The KonaKart login() method will * perform the credential check.</li> * <li>A positive number for the login attempt to pass. The KonaKart login() will not check * credentials, and will log in the customer, returning a valid session id.</li> * </ul> * This method may need to be modified slightly depending on the structure of your LDAP. The * example works when importing the exampleData.ldif file in the LDAP module jar: * * dn: cn=Robert Smith,ou=people,dc=example,dc=com<br/> * objectclass: inetOrgPerson<br/> * cn: Robert Smith<br/> * cn: Robert J Smith<br/> * cn: bob smith<br/> * sn: smith<br/> * uid: rjsmith<br/> * userpassword: rJsmitH<br/> * carlicense: HISCAR 123<br/> * homephone: 555-111-2222<br/> * mail: r.smith@example.com<br/> * mail: rsmith@example.com<br/> * mail: bob.smith@example.com<br/> * description: swell guy<br/> * * The code attempts to connect to LDAP using the username, password and URL in the * configuration variables set when the module was installed through the admin app.<br/> * * After having connected, the person object is searched for using the email address of the * user. If found we use the "cn" attribute and the password of the user to attempt to bind to * LDAP. If the bind is successful, we return a positive number which means that authentication * was successful. * * @param emailAddr * The user name required to log in * @param password * The log in password * @return Returns an integer * @throws Exception */ public int checkCredentials(String emailAddr, String password) throws Exception { DirContext ctx = null; try { Hashtable<String, String> environment = new Hashtable<String, String>(); if (log.isDebugEnabled()) { log.debug("LDAP connection URL = " + url); log.debug("LDAP user name = " + ldapUserName); log.debug("LDAP person object distinguished name (DN) = " + personDN); } if (ldapUserName == null) { throw new KKException( "Cannot access LDAP because the MODULE_OTHER_LDAP_USER_NAME configuration variable hasn't been set."); } if (ldapPassword == null) { throw new KKException( "Cannot access LDAP because the MODULE_OTHER_LDAP_PASSWORD configuration variable hasn't been set."); } if (url == null) { throw new KKException( "Cannot access LDAP because the MODULE_OTHER_LDAP_URL configuration variable hasn't been set."); } if (personDN == null) { throw new KKException( "Cannot validate through LDAP because the MODULE_OTHER_LDAP_PERSON_DN (Distinguished Name of Person Object) configuration variable hasn't been set."); } environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); environment.put(Context.SECURITY_AUTHENTICATION, "simple"); environment.put(Context.PROVIDER_URL, url); environment.put(Context.SECURITY_PRINCIPAL, ldapUserName); environment.put(Context.SECURITY_CREDENTIALS, ldapPassword); /* * connect to LDAP using the credentials and connection string from the configuration * variables */ try { ctx = new InitialDirContext(environment); } catch (Exception e) { log.error("Cannot connect to LDAP", e); return -1; } /* Specify the search filter on the eMail address */ String filter = "(mail=" + emailAddr + ")"; /* * limit returned attributes to those we care about. In this case we only require the * "cn" attribute which we will use to attempt to bind the user in order to validate his * password */ String[] attrIDs = { "cn" }; SearchControls ctls = new SearchControls(); ctls.setReturningAttributes(attrIDs); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); /* Search for objects using filter and controls */ NamingEnumeration<SearchResult> answer = ctx.search(personDN, filter, ctls); /* close the connection */ ctx.close(); if (answer == null || !answer.hasMore()) { return -1; } SearchResult sr = answer.next(); Attributes attrs = sr.getAttributes(); String cn = attrs.get("cn").toString(); if (log.isDebugEnabled()) { log.debug("cn of user with eMail (" + emailAddr + ") is " + cn); } /* * cn could be in the format "cn: Peter Smith, Pete Smith, Smithy" so we need to capture * just the first entry */ if (cn != null) { if (cn.contains(",")) { cn = cn.split(",")[0]; if (cn.contains(":")) { cn = cn.split(":")[1]; } } else if (cn.contains(":")) { cn = cn.split(":")[1]; } } if (log.isDebugEnabled()) { log.debug("Cleaned cn of user with eMail (" + emailAddr + ") is " + cn); } /* Now we try to bind as the user */ String userName = "cn=" + cn + "," + personDN; if (log.isDebugEnabled()) { log.debug("LDAP user name of user with eMail (" + emailAddr + ") is " + userName); } /* Bind as the user */ environment.put(Context.SECURITY_PRINCIPAL, userName); environment.put(Context.SECURITY_CREDENTIALS, password); try { ctx = new InitialDirContext(environment); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Could not bind user " + userName); } return -1; } ctx.close(); if (log.isDebugEnabled()) { log.debug("user with eMail (" + emailAddr + ") was successfully authenticated using LDAP"); } return 1; } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { log.error("Received an exception while closing the LDAP DirContext", e); } } } }
From source file:edu.umich.ctools.sectionsUtilityTool.SectionUtilityToolFilter.java
private boolean ldapAuthorizationVerification(String user) { M_log.debug("ldapAuthorizationVerification(): called"); boolean isAuthorized = false; DirContext dirContext = null; NamingEnumeration listOfPeopleInAuthGroup = null; NamingEnumeration allSearchResultAttributes = null; NamingEnumeration simpleListOfPeople = null; Hashtable<String, String> env = new Hashtable<String, String>(); if (!isEmpty(providerURL) && !isEmpty(mcommunityGroup)) { env.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_CTX_FACTORY); env.put(Context.PROVIDER_URL, providerURL); } else {/* www . j av a 2 s. co m*/ M_log.error( " [ldap.server.url] or [mcomm.group] properties are not set, review the sectionsToolPropsLessSecure.properties file"); return isAuthorized; } try { dirContext = new InitialDirContext(env); String[] attrIDs = { "member" }; SearchControls searchControls = new SearchControls(); searchControls.setReturningAttributes(attrIDs); searchControls.setReturningObjFlag(true); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchBase = OU_GROUPS; String filter = "(&(cn=" + mcommunityGroup + ") (objectclass=rfc822MailGroup))"; listOfPeopleInAuthGroup = dirContext.search(searchBase, filter, searchControls); String positiveMatch = "uid=" + user + ","; outerloop: while (listOfPeopleInAuthGroup.hasMore()) { SearchResult searchResults = (SearchResult) listOfPeopleInAuthGroup.next(); allSearchResultAttributes = (searchResults.getAttributes()).getAll(); while (allSearchResultAttributes.hasMoreElements()) { Attribute attr = (Attribute) allSearchResultAttributes.nextElement(); simpleListOfPeople = attr.getAll(); while (simpleListOfPeople.hasMoreElements()) { String val = (String) simpleListOfPeople.nextElement(); if (val.indexOf(positiveMatch) != -1) { isAuthorized = true; break outerloop; } } } } return isAuthorized; } catch (NamingException e) { M_log.error("Problem getting attribute:" + e); return isAuthorized; } finally { try { if (simpleListOfPeople != null) { simpleListOfPeople.close(); } } catch (NamingException e) { M_log.error( "Problem occurred while closing the NamingEnumeration list \"simpleListOfPeople\" list ", e); } try { if (allSearchResultAttributes != null) { allSearchResultAttributes.close(); } } catch (NamingException e) { M_log.error( "Problem occurred while closing the NamingEnumeration \"allSearchResultAttributes\" list ", e); } try { if (listOfPeopleInAuthGroup != null) { listOfPeopleInAuthGroup.close(); } } catch (NamingException e) { M_log.error( "Problem occurred while closing the NamingEnumeration \"listOfPeopleInAuthGroup\" list ", e); } try { if (dirContext != null) { dirContext.close(); } } catch (NamingException e) { M_log.error("Problem occurred while closing the \"dirContext\" object", e); } } }
From source file:org.jsecurity.realm.activedirectory.ActiveDirectoryRealm.java
private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException { Set<String> roleNames; roleNames = new LinkedHashSet<String>(); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String userPrincipalName = username; if (principalSuffix != null) { userPrincipalName += principalSuffix; }/*from w w w.ja v a 2 s. c o m*/ String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))"; NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, 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:eu.uqasar.util.ldap.LdapManager.java
private <T extends LdapEntity> List<T> getLdapEntities(int maximum, final String baseDN, final String preferredFilter, Class<T> clazz, Comparator<T> comparator) throws NamingException { if (maximum <= 0) { return Collections.emptyList(); }//from w w w . ja va2s . c o m List<T> entities = new ArrayList<>(); NamingEnumeration<SearchResult> results = searchLDAP(baseDN, preferredFilter); while (results.hasMoreElements() && entities.size() < maximum) { try { SearchResult group = results.next(); Constructor<T> constructor = clazz.getConstructor(Attributes.class, LdapSettings.class); T entity = constructor.newInstance(group.getAttributes(), settings); entities.add(entity); } catch (LdapReferralException ex) { logger.warn(ex.getMessage(), ex); } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { logger.error(ex.getMessage(), ex); } } Collections.sort(entities, comparator); return entities; }
From source file:org.sipfoundry.sipxconfig.bulk.ldap.UserMapper.java
public Collection<String> getGroupNames(SearchResult sr) throws NamingException { Set<String> groupNames = new HashSet<String>(); // group names in the current entry Attributes attrs = sr.getAttributes(); Set<String> entryGroups = replaceWhitespace(getValues(attrs, Index.USER_GROUP)); if (entryGroups != null) { groupNames.addAll(entryGroups);/*ww w . j a v a2s . c o m*/ } // group names found in distinguished name if (sr.isRelative()) { String name = sr.getName(); LdapName ldapName = new LdapName(name); List<Rdn> rdns = ldapName.getRdns(); for (Rdn rdn : rdns) { Attributes rdnsAttributes = rdn.toAttributes(); Set<String> rdnsGroups = replaceWhitespace(getValues(rdnsAttributes, Index.USER_GROUP)); if (rdnsGroups != null) { groupNames.addAll(rdnsGroups); } } } //only if there is no already defined group, add the default user group if (groupNames.isEmpty()) { String defaultGroupName = getAttrMap().getDefaultGroupName(); if (defaultGroupName != null) { groupNames.add(defaultGroupName); } } return groupNames; }
From source file:org.springframework.ldap.samples.article.dao.TraditionalPersonDaoImpl.java
public List findAll() { DirContext ctx = createAnonymousContext(); LinkedList list = new LinkedList(); NamingEnumeration results = null; try {// w w w . ja v a 2s . c o m SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); results = ctx.search("", "(objectclass=person)", controls); while (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); String dn = searchResult.getName(); Attributes attributes = searchResult.getAttributes(); list.add(mapToPerson(dn, attributes)); } } catch (NamingException e) { throw new RuntimeException(e); } finally { if (results != null) { try { results.close(); } catch (Exception e) { // Never mind this. } } if (ctx != null) { try { ctx.close(); } catch (Exception e) { // Never mind this. } } } return list; }
From source file:org.springframework.ldap.demo.dao.PersonDaoImpl.java
public List<Person> findAll() { DirContext ctx = createAnonymousContext(); LinkedList<Person> list = new LinkedList<Person>(); NamingEnumeration<?> results = null; try {/*from w w w. jav a2 s .c o m*/ SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); results = ctx.search("", "(objectclass=person)", controls); while (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); String dn = searchResult.getName(); Attributes attributes = searchResult.getAttributes(); list.add(mapToPerson(dn, attributes)); } } catch (NamingException e) { throw new RuntimeException(e); } finally { if (results != null) { try { results.close(); } catch (Exception e) { // Never mind this. } } if (ctx != null) { try { ctx.close(); } catch (Exception e) { // Never mind this. } } } return list; }
From source file:org.eclipse.skalli.core.user.ldap.LDAPClient.java
private User processEntry(SearchResult entry) throws NamingException { User user = new User(); Attributes attrs = entry.getAttributes(); Attribute attrBits = attrs.get(LDAPAttributeNames.BITS.getLdapKey()); if (attrBits != null) { long lng = Long.parseLong(attrBits.get(0).toString()); long secondBit = lng & 2; // get bit 2 if (secondBit != 0) { // User not enabled return null; }/*from w w w . j a va 2 s .c om*/ } user.setUserId(StringUtils.lowerCase(getStringValue(attrs, LDAPAttributeNames.USERID))); user.setFirstname(getStringValue(attrs, LDAPAttributeNames.FIRSTNAME)); user.setLastname(getStringValue(attrs, LDAPAttributeNames.LASTNAME)); user.setEmail(getStringValue(attrs, LDAPAttributeNames.EMAIL)); user.setTelephone(getStringValue(attrs, LDAPAttributeNames.TELEPHONE)); user.setMobile(getStringValue(attrs, LDAPAttributeNames.MOBILE)); user.setRoom(getStringValue(attrs, LDAPAttributeNames.ROOM)); user.setLocation(getStringValue(attrs, LDAPAttributeNames.LOCATION)); user.setDepartment(getStringValue(attrs, LDAPAttributeNames.DEPARTMENT)); user.setCompany(getStringValue(attrs, LDAPAttributeNames.COMPANY)); user.setSip(getStringValue(attrs, LDAPAttributeNames.SIP)); return user; }
From source file:org.pentaho.platform.plugin.services.security.userrole.ldap.transform.SearchResultToAttrValueList.java
public Object transform(final Object obj) { Object transformed = obj;/*from w w w . ja va 2s.com*/ if (obj instanceof SearchResult) { transformed = new HashSet(); Set valueSet = (Set) transformed; SearchResult res = (SearchResult) obj; if (SearchResultToAttrValueList.logger.isDebugEnabled()) { SearchResultToAttrValueList.logger.debug(Messages.getInstance().getString( "SearchResultToAttrValueList.DEBUG_ATTRIBUTES_FROM_SEARCHRESULT", (null != res.getAttributes()) ? res.getAttributes().toString() : "null")); //$NON-NLS-1$ //$NON-NLS-2$ } Attribute attr = res.getAttributes().get(attributeName); if (SearchResultToAttrValueList.logger.isDebugEnabled()) { SearchResultToAttrValueList.logger .debug(Messages.getInstance().getString("SearchResultToAttrValueList.DEBUG_ATTRIBUTE_VALUE", attributeName, (null != attr) ? attr.toString() : "null")); //$NON-NLS-1$ //$NON-NLS-2$ } if (attr != null) { // check for null as node might not have attribute we're looking for try { NamingEnumeration values = attr.getAll(); while (values.hasMore()) { // if tokenName was specified, extract from value; otherwise // store value unchanged Object value = values.next(); if (StringUtils.hasLength(tokenName)) { if ((null != value) && (value instanceof String)) { String tokenValue = extract((String) value, tokenName); if (null != tokenValue) { valueSet.add(tokenValue); } } else { if (SearchResultToAttrValueList.logger.isWarnEnabled()) { SearchResultToAttrValueList.logger.warn(Messages.getInstance() .getString("SearchResultToAttrValueList.WARN_ATTRIBUTE_NOT_A_STRING")); //$NON-NLS-1$ } } } else { if (null != value) { valueSet.add(value.toString()); } } } } catch (NamingException e) { if (SearchResultToAttrValueList.logger.isErrorEnabled()) { SearchResultToAttrValueList.logger.error(Messages.getInstance() .getErrorString("SearchResultToAttrValueList.ERROR_0001_NAMING_EXCEPTION"), e); //$NON-NLS-1$ } } } return transformed; } return transformed; }