List of usage examples for javax.naming.directory SearchResult getAttributes
public Attributes getAttributes()
From source file:fedora.server.security.servletfilters.ldap.FilterLdap.java
private Boolean processNamingEnumeration(NamingEnumeration ne, String password, Boolean authenticated, Map map) {//from ww w. j a va2s. c o m String m = FilterSetup.getFilterNameAbbrev(FILTER_NAME) + " processNamingEnumeration() "; log.debug(m + ">"); try { boolean errorOnSomeComparison = false; while (ne.hasMoreElements()) { log.debug(m + "another element"); SearchResult s = null; try { Object o = ne.nextElement(); log.debug(m + "got a " + o.getClass().getName()); s = (SearchResult) o; } catch (Throwable th) { log.error(m + "naming enum contains obj not SearchResult"); continue; } Attributes attributes = s.getAttributes(); getAttributes(attributes, map); if (individualUserComparison()) { Boolean temp = null; try { temp = comparePassword(attributes, password, PASSWORD); log.debug(m + "-this- comp yields " + temp); if (authenticated != null && !authenticated) { log.debug(m + "keeping prev failed authn"); } else { log.debug(m + "replacing prvsuccess or null authn"); if (errorOnSomeComparison) { log.debug(m + "errorOnSomeComparison==" + errorOnSomeComparison); } else { authenticated = temp; } } } catch (Throwable th) { log.debug(m + "in iUC conditional, caught throwable th==" + th); errorOnSomeComparison = true; authenticated = null; } } } if (individualUserComparison()) { if (errorOnSomeComparison) { log.debug(m + "exception, so assuring authenticated==" + authenticated); authenticated = null; map.clear(); } else if (authenticated == null) { authenticated = Boolean.FALSE; log.debug(m + "no passwd attr found, so authenticated==" + authenticated); } } } catch (Throwable th) { // play it safe: map.clear(); if (authenticated != null && authenticated) { // drop an earlier authentication, before exception was thrown authenticated = null; } // but leave alone a earlier -failed- authentication if (LOG_STACK_TRACES) { log.error(m + "ldap filter failure", th); } else { log.error(m + "ldap filter failure" + th.getMessage()); } } finally { log.debug(m + "< authenticated==" + authenticated + " map==" + map); } return authenticated; }
From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java
/** * attempts to get the users credentials from the users context * <p/>/*from ww w.ja va 2 s . c om*/ * NOTE: this is not an user authenticated operation * * @param username * @return * @throws LoginException */ @SuppressWarnings("unchecked") private String getUserCredentials(String username) throws LoginException { String ldapCredential = null; SearchControls ctls = new SearchControls(); ctls.setCountLimit(1); ctls.setDerefLinkFlag(true); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); try { Object[] filterArguments = { _userObjectClass, _userIdAttribute, username }; NamingEnumeration results = _rootContext.search(_userBaseDn, OBJECT_CLASS_FILTER, filterArguments, ctls); debug("Found user?: " + results.hasMoreElements()); if (!results.hasMoreElements()) { throw new LoginException("User not found."); } SearchResult result = findUser(username); Attributes attributes = result.getAttributes(); setDemographicAttributes(attributes); Attribute attribute = attributes.get(_userPasswordAttribute); if (attribute != null) { try { byte[] value = (byte[]) attribute.get(); ldapCredential = new String(value); } catch (NamingException e) { LOG.info("no password available under attribute: " + _userPasswordAttribute); } } } catch (NamingException e) { throw new LoginException("Root context binding failure."); } debug("user cred is present: " + (ldapCredential != null)); return ldapCredential; }
From source file:com.wfp.utils.LDAPUtils.java
@SuppressWarnings("unchecked") public static Map<String, String> parseDataAsMap(NamingEnumeration searchResults) { Map<String, String> resultAttrMap = null; int totalResultLogger = 0; if (searchResults == null) { return null; }/* w w w.ja va2s. c o m*/ // Loop through the search results while (searchResults.hasMoreElements()) { SearchResult sr = null; try { sr = (SearchResult) searchResults.next(); } catch (NamingException e1) { Logger.error("No Search results on LDAP ", LDAPUtils.class); } if (sr == null) { Logger.error("No Search results on LDAP ", LDAPUtils.class); return null; } Attributes attrs = sr.getAttributes(); if (attrs != null) { if (resultAttrMap == null) { resultAttrMap = new HashMap<String, String>(); } try { for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); for (NamingEnumeration e = attr.getAll(); e.hasMore(); totalResultLogger++) { String attrValue = (String) e.next(); resultAttrMap.put(attr.getID(), attrValue); } } } catch (NamingException e) { Logger.error("Error ocuring while reading the attributes ", LDAPUtils.class, e); } } else { Logger.info("No attributes found on LDAP", LDAPUtils.class); } } return resultAttrMap; }
From source file:com.wfp.utils.LDAPUtils.java
@SuppressWarnings("unchecked") public static List parseDataAsList(NamingEnumeration searchResults) { //Logger.info("Formatting the data as List", LDAPUtils.class ); List<String> resultAttr = null; int totalResultLogger = 0; if (searchResults == null) { return null; }/* w w w .j a v a2s . co m*/ // Loop through the search results while (searchResults.hasMoreElements()) { SearchResult sr = null; try { sr = (SearchResult) searchResults.next(); } catch (NamingException e1) { Logger.error("No Search results on LDAP ", LDAPUtils.class); } if (sr == null) { Logger.error("No Search results on LDAP ", LDAPUtils.class); return null; } Attributes attrs = sr.getAttributes(); if (attrs != null) { if (resultAttr == null) { resultAttr = new ArrayList(); } try { for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); for (NamingEnumeration e = attr.getAll(); e.hasMore(); totalResultLogger++) { String attrValue = (String) e.next(); resultAttr.add(attrValue); } } } catch (NamingException e) { Logger.error("Error ocuring while reading the attributes ", LDAPUtils.class, e); } } else { Logger.info("No attributes found on LDAP", LDAPUtils.class); } } return resultAttr; }
From source file:org.apache.manifoldcf.authorities.authorities.sharepoint.SharePointADAuthority.java
/** Get the AD-derived access tokens for a user and domain */ protected List<String> getADTokens(String userPart, String domainPart, String userName) throws NameNotFoundException, NamingException, ManifoldCFException { // Now, look through the rules for the matching domain controller String domainController = null; for (DCRule rule : dCRules) { String suffix = rule.getSuffix(); if (suffix.length() == 0 || domainPart.toLowerCase(Locale.ROOT).endsWith(suffix.toLowerCase(Locale.ROOT)) && (suffix.length() == domainPart.length() || domainPart.charAt((domainPart.length() - suffix.length()) - 1) == '.')) { domainController = rule.getDomainControllerName(); break; }//from w w w . java2 s.c o m } if (domainController == null) // No AD user return null; // Look up connection parameters DCConnectionParameters dcParams = dCConnectionParameters.get(domainController); if (dcParams == null) // No AD user return null; // Use the complete fqn if the field is the "userPrincipalName" String userBase; String userACLsUsername = dcParams.getUserACLsUsername(); if (userACLsUsername != null && userACLsUsername.equals("userPrincipalName")) { userBase = userName; } else { userBase = userPart; } //Build the DN searchBase from domain part StringBuilder domainsb = new StringBuilder(); int j = 0; while (true) { if (j > 0) domainsb.append(","); int k = domainPart.indexOf(".", j); if (k == -1) { domainsb.append("DC=").append(ldapEscape(domainPart.substring(j))); break; } domainsb.append("DC=").append(ldapEscape(domainPart.substring(j, k))); j = k + 1; } // Establish a session with the selected domain controller LdapContext ctx = createDCSession(domainController); //Get DistinguishedName (for this method we are using DomainPart as a searchBase ie: DC=qa-ad-76,DC=metacarta,DC=com") String searchBase = getDistinguishedName(ctx, userBase, domainsb.toString(), userACLsUsername); if (searchBase == null) return null; //specify the LDAP search filter String searchFilter = "(objectClass=user)"; //Create the search controls for finding the access tokens SearchControls searchCtls = new SearchControls(); //Specify the search scope, must be base level search for tokenGroups searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE); //Specify the attributes to return String returnedAtts[] = { "tokenGroups", "objectSid" }; searchCtls.setReturningAttributes(returnedAtts); //Search for tokens. Since every user *must* have a SID, the "no user" detection should be safe. NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls); List<String> theGroups = new ArrayList<String>(); String userToken = userTokenFromLoginName(domainPart + "\\" + userPart); if (userToken != null) theGroups.add(userToken); //Loop through the search results while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); //the sr.GetName should be null, as it is relative to the base object Attributes attrs = sr.getAttributes(); if (attrs != null) { try { for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); for (NamingEnumeration e = attr.getAll(); e.hasMore();) { String sid = sid2String((byte[]) e.next()); String token = attr.getID().equals("objectSid") ? userTokenFromSID(sid) : groupTokenFromSID(sid); theGroups.add(token); } } } catch (NamingException e) { throw new ManifoldCFException(e.getMessage(), e); } } } if (theGroups.size() == 0) return null; // User is in AD, so add the 'everyone' group theGroups.add(everyoneGroup()); return theGroups; }
From source file:com.wfp.utils.LDAPUtils.java
public static Map<String, Object> parseDataAsMap(NamingEnumeration searchResults, String listValues) { //Logger.info("Formatting the data as MAP", LDAPUtils.class); Map<String, Object> resultAttrMap = null; int totalResultLogger = 0; if (searchResults == null) { return null; }/*from ww w .j a va2 s . com*/ // Loop through the search results while (searchResults.hasMoreElements()) { SearchResult sr = null; try { sr = (SearchResult) searchResults.next(); } catch (NamingException e1) { Logger.error("No Search results on LDAP ", LDAPUtils.class); } if (sr == null) { Logger.error("No Search results on LDAP ", LDAPUtils.class); return null; } Attributes attrs = sr.getAttributes(); if (attrs != null) { if (resultAttrMap == null) { resultAttrMap = new HashMap<String, Object>(); } try { for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); for (NamingEnumeration e = attr.getAll(); e.hasMore(); totalResultLogger++) { String attrValue = (String) e.next(); List<String> attrValuesList = null; if (listValues.indexOf(attr.getID()) >= 0) { attrValuesList = resultAttrMap.get(attr.getID()) == null ? null : (List<String>) resultAttrMap.get(attr.getID()); if (attrValuesList == null) { attrValuesList = new ArrayList<String>(); } attrValuesList.add(attrValue); resultAttrMap.put(attr.getID(), attrValuesList); } else { resultAttrMap.put(attr.getID(), attrValue); } } } } catch (NamingException e) { Logger.error("Error ocuring while reading the attributes ", LDAPUtils.class, e); } } else { Logger.info("No attributes found on LDAP", LDAPUtils.class); } } return resultAttrMap; }
From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java
private ConcurrentHashMap<String, List<String>> buildRoleMemberOfMap(DirContext dirContext) { Object[] filterArguments = { _roleObjectClass }; SearchControls ctls = new SearchControls(); ctls.setDerefLinkFlag(true);/*from w w w . j av a 2 s .co m*/ ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ConcurrentHashMap<String, List<String>> roleMemberOfMap = new ConcurrentHashMap<String, List<String>>(); try { NamingEnumeration<SearchResult> results = dirContext.search(_roleBaseDn, _roleMemberFilter, ctls); while (results.hasMoreElements()) { SearchResult result = results.nextElement(); Attributes attributes = result.getAttributes(); if (attributes == null) { continue; } Attribute roleAttribute = attributes.get(_roleNameAttribute); Attribute memberAttribute = attributes.get(_roleMemberAttribute); if (roleAttribute == null || memberAttribute == null) { continue; } NamingEnumeration role = roleAttribute.getAll(); NamingEnumeration members = memberAttribute.getAll(); if (!role.hasMore() || !members.hasMore()) { continue; } String roleName = (String) role.next(); if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) { roleName = roleName.replace(_rolePrefix, ""); } while (members.hasMore()) { String member = (String) members.next(); Matcher roleMatcher = rolePattern.matcher(member); if (!roleMatcher.find()) { continue; } String roleMember = roleMatcher.group(1); List<String> memberOf; if (roleMemberOfMap.containsKey(roleMember)) { memberOf = roleMemberOfMap.get(roleMember); } else { memberOf = new ArrayList<String>(); } memberOf.add(roleName); roleMemberOfMap.put(roleMember, memberOf); } } } catch (NamingException e) { e.printStackTrace(); } return roleMemberOfMap; }
From source file:com.wfp.utils.LDAPUtils.java
@SuppressWarnings("unchecked") public static Map<String, Map<String, String>> parseDataAsMap(NamingEnumeration searchResults, String optionalKey, String uniqueKey, String[] attrArray) { Logger.debug("Formatting the data as MAP", LDAPUtils.class); Map<String, Map<String, String>> resultMap = null; int totalResultLogger = 0; if (searchResults == null) { return null; }/*w ww .j a va2s .c o m*/ // Loop through the search results while (searchResults.hasMoreElements()) { SearchResult sr = null; try { sr = (SearchResult) searchResults.next(); } catch (NamingException e1) { Logger.error("No Search results on LDAP ", LDAPUtils.class); } if (sr == null) { Logger.error("No Search results on LDAP ", LDAPUtils.class); return null; } Attributes attrs = sr.getAttributes(); if (attrs != null) { if (resultMap == null) { resultMap = new HashMap<String, Map<String, String>>(); } try { Map<String, String> resultAttrMap = new HashMap(); for (String attr : attrArray) { if (resultAttrMap.get(attr) == null) { attrs.get(attr); resultAttrMap.put(attr, ""); } } for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); for (NamingEnumeration e = attr.getAll(); e.hasMore(); totalResultLogger++) { String attrValue = (String) e.next(); //if it is external id if (attr.getID().equals(EXTERNAL_ID)) { if (attrValue.contains(COMPASS_ID)) { resultAttrMap.put(attr.getID(), attrValue.replace(COMPASS_ID, "")); break; } else resultAttrMap.put(attr.getID(), "inValidFormat"); } resultAttrMap.put(attr.getID(), attrValue); } } if (optionalKey != null && !StringUtils.isNull(resultAttrMap.get(optionalKey))) { resultMap.put(resultAttrMap.get(optionalKey), resultAttrMap); } else { resultAttrMap.put("compasId", ""); resultMap.put(resultAttrMap.get(uniqueKey), resultAttrMap); } } catch (NamingException e) { Logger.error("Error ocuring while reading the attributes ", LDAPUtils.class, e); } } else { Logger.info("No attributes found on LDAP", LDAPUtils.class); } } return resultMap; }
From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java
@SuppressWarnings("unchecked") private List getUserRolesByDn(DirContext dirContext, String userDn, String username) throws LoginException, NamingException { List<String> roleList = new ArrayList<String>(); if (dirContext == null || _roleBaseDn == null || (_roleMemberAttribute == null && _roleUsernameMemberAttribute == null) || _roleObjectClass == null) { LOG.warn(// ww w . ja v a 2 s.c o m "JettyCachingLdapLoginModule: No user roles found: roleBaseDn, roleObjectClass and roleMemberAttribute or roleUsernameMemberAttribute must be specified."); addSupplementalRoles(roleList); return roleList; } String[] attrIDs = { _roleNameAttribute }; SearchControls ctls = new SearchControls(); ctls.setReturningAttributes(attrIDs); ctls.setDerefLinkFlag(true); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = OBJECT_CLASS_FILTER; final NamingEnumeration results; if (null != _roleUsernameMemberAttribute) { Object[] filterArguments = { _roleObjectClass, _roleUsernameMemberAttribute, username }; results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls); } else { Object[] filterArguments = { _roleObjectClass, _roleMemberAttribute, userDn }; results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls); } while (results.hasMoreElements()) { SearchResult result = (SearchResult) results.nextElement(); Attributes attributes = result.getAttributes(); if (attributes == null) { continue; } Attribute roleAttribute = attributes.get(_roleNameAttribute); if (roleAttribute == null) { continue; } NamingEnumeration roles = roleAttribute.getAll(); while (roles.hasMore()) { if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) { String role = (String) roles.next(); roleList.add(role.replace(_rolePrefix, "")); } else { roleList.add((String) roles.next()); } } } addSupplementalRoles(roleList); if (_nestedGroups) { roleList = getNestedRoles(dirContext, roleList); } if (roleList.size() < 1) { LOG.warn("JettyCachingLdapLoginModule: User '" + username + "' has no role membership; role query configuration may be incorrect"); } else { debug("JettyCachingLdapLoginModule: User '" + username + "' has roles: " + roleList); } return roleList; }
From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java
@Override public void doUpdateCredentialByAdmin(String userName, Object newCredential) throws UserStoreException { if (!isSSLConnection) { logger.warn("Unsecured connection is being used. Password operations will fail"); }//from w w w.ja v a 2 s . com 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 = "(&" + 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; if (newCredential != null) { mods = new ModificationItem[1]; mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE, createUnicodePassword((String) newCredential))); 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); } }