List of usage examples for javax.naming.directory SearchResult getAttributes
public Attributes getAttributes()
From source file:com.adito.activedirectory.ActiveDirectoryUserDatabase.java
private void loadRoles(String filter, InitialLdapContext context, boolean removeMissingEntries) throws Exception { final Collection<String> groupNames = groupContainer.retrievePrincipalNames(); PagedResultMapper mapper = new AbstractPagedResultMapper() { public void mapSearchResult(SearchResult searchResult) throws NamingException { String dn = searchResult.getNameInNamespace(); Attributes attributes = searchResult.getAttributes(); String commonName = getAttributeValue(attributes, COMMON_NAME_ATTRIBUTE); if (commonName.length() != 0) { Long rid = ActiveDirectoryGroup .getRIDFromSID((byte[]) attributes.get(OBJECT_SID_ATTRIBUTE).get()); ActiveDirectoryGroup group = new ActiveDirectoryGroup(commonName, dn, getEscapedDn(dn), rid, getRealm());/*from ww w . j a v a2 s .co m*/ String[] parents = getParents(attributes); String key = groupContainer.storeGroup(group, parents); groupNames.remove(key); } } }; try { String replacedFilter = buildGroupFilter(filter); PagedResultTemplate pagedResultTemplate = configuration.getPagedResultTemplate(); pagedResultTemplate.search(context, replacedFilter, GROUP_ATTRS, mapper); } finally { if (removeMissingEntries) { groupContainer.updateRemovedGroups(groupNames); } } }
From source file:org.apache.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java
protected boolean authenticate(String username) throws Exception { DirContext context = open();//ww w.j a va 2s . c om 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.manifoldcf.authorities.authorities.sharepoint.SharePointADAuthority.java
/** Obtain the DistinguishedName for a given user logon name. *@param ctx is the ldap context to use./* ww w . j a va 2 s. c o m*/ *@param userName (Domain Logon Name) is the user name or identifier. *@param searchBase (Full Domain Name for the search ie: DC=qa-ad-76,DC=metacarta,DC=com) *@return DistinguishedName for given domain user logon name. * (Should throws an exception if user is not found.) */ protected String getDistinguishedName(LdapContext ctx, String userName, String searchBase, String userACLsUsername) throws ManifoldCFException { String returnedAtts[] = { "distinguishedName" }; String searchFilter = "(&(objectClass=user)(" + userACLsUsername + "=" + userName + "))"; SearchControls searchCtls = new SearchControls(); searchCtls.setReturningAttributes(returnedAtts); //Specify the search scope searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setReturningAttributes(returnedAtts); try { NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); if (attrs != null) { String dn = attrs.get("distinguishedName").get().toString(); return dn; } } return null; } catch (NamingException e) { throw new ManifoldCFException(e.getMessage(), e); } }
From source file:org.olat.ldap.LDAPLoginManagerImpl.java
/** * Creates list of all LDAP Users or changed Users since syncTime Configuration: userAttr = olatextconfig.xml (property=userAttrs) LDAP Base = olatextconfig.xml * (property=ldapBase)/*from w w w . j av a 2 s .c o m*/ * * @param syncTime The time to search in LDAP for changes since this time. SyncTime has to formatted: JJJJMMddHHmm * @param ctx The LDAP system connection, if NULL or closed NamingExecpiton is thrown * @return Returns list of Arguments of found users or empty list if search fails or nothing is changed * @throws NamingException */ public List<Attributes> getUserAttributesModifiedSince(final Date syncTime, final LdapContext ctx) { final String objctClass = LDAPLoginModule.getLdapUserObjectClass(); final StringBuilder filter = new StringBuilder(); if (syncTime == null) { filter.append("(objectClass=").append(objctClass).append(")"); } else { final String dateFormat = LDAPLoginModule.getLdapDateFormat(); final SimpleDateFormat generalizedTimeFormatter = new SimpleDateFormat(dateFormat); generalizedTimeFormatter.setTimeZone(UTC_TIME_ZONE); final String syncTimeForm = generalizedTimeFormatter.format(syncTime); filter.append("(&(objectClass=").append(objctClass).append(")(|("); filter.append(LDAPLoginModule.getLdapUserLastModifiedTimestampAttribute()).append(">=") .append(syncTimeForm); filter.append(")("); filter.append(LDAPLoginModule.getLdapUserCreatedTimestampAttribute()).append(">=").append(syncTimeForm); filter.append(")))"); } final List<Attributes> ldapUserList = new ArrayList<Attributes>(); searchInLdap(new LdapVisitor() { public void visit(final SearchResult result) { ldapUserList.add(result.getAttributes()); } }, filter.toString(), LDAPLoginModule.getUserAttrs(), ctx); return ldapUserList; }
From source file:com.adito.activedirectory.ActiveDirectoryUserDatabase.java
private void loadUsers(final String filter, InitialLdapContext context, final boolean removeMissingEntries) throws NamingException { final Collection<String> usernames = userContainer.retrievePrincipalNames(); PagedResultMapper mapper = new AbstractPagedResultMapper() { public void mapSearchResult(SearchResult searchResult) throws NamingException, UserDatabaseException { String dn = searchResult.getNameInNamespace(); ActiveDirectoryUser user = populateActiveDirectoryUser(dn, searchResult.getAttributes()); String key = userContainer.storePrincipal(user); usernames.remove(key);//from w w w . jav a 2 s. c o m if (logger.isDebugEnabled()) { logger.debug("Found user " + user); } } }; try { String replacedFilter = buildUserFilter(filter); PagedResultTemplate pagedResultTemplate = configuration.getPagedResultTemplate(); pagedResultTemplate.search(context, replacedFilter, USER_ATTRS, mapper); } finally { if (removeMissingEntries) { userContainer.updateRemovedPrincipals(usernames); } } }
From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java
/** * Fetches the supplied user DN./* w ww .jav a 2 s . c o m*/ * * @param uid the user id * @return the user DN for the supplied uid * @throws NamingException LDAP error obtaining user information. */ protected String selectUserDN(InitialLdapContext ctx, String uid) throws NamingException { String dn = null; String principalUidAttrName = this.getPrincipalUidAttributeID(); String usersCtxDN = this.getUsersCtxDN(); try { // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr); // This gives more control over search behavior : NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalUidAttrName + "=" + uid + "))", getSearchControls()); while (answer.hasMore()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); Attribute uidAttr = attrs.get(principalUidAttrName); if (uidAttr == null) { logger.warn("Invalid user uid attribute '" + principalUidAttrName + "'"); continue; } String uidValue = uidAttr.get().toString(); if (uidValue != null) { dn = sr.getName() + "," + usersCtxDN; if (logger.isDebugEnabled()) logger.debug("Found user '" + principalUidAttrName + "=" + uidValue + "' for user '" + uid + "' DN=" + dn); } else { if (logger.isDebugEnabled()) logger.debug("User not found for user '" + uid + "'"); } } } catch (NamingException e) { if (logger.isDebugEnabled()) logger.debug("Failed to locate user", e); } return dn; }
From source file:org.swordess.ldap.odm.core.SessionImpl.java
@Override public List<Map<String, Object>> search(String context, String filter, String[] returningAttrs) { if (null == filter) { return null; }//from w ww.j a va 2 s . c om LogUtils.debug(LOG, String.format("search %s with filter=%s, returningAttrs=%s", context, filter, Arrays.toString(returningAttrs))); SearchControls ctrl = new SearchControls(); ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE); ctrl.setReturningAttributes(returningAttrs); try { List<Map<String, Object>> retVal = new ArrayList<Map<String, Object>>(); NamingEnumeration<SearchResult> results = ctx.search(context, filter, ctrl); while (results.hasMore()) { try { SearchResult result = results.next(); retVal.add(fromAttributesToMap(result.getAttributes())); } catch (NamingException e) { LogUtils.error(LOG, "Unable to construct the map", e); } } return retVal; } catch (NamingException e) { throw new SessionException(e.getMessage(), e); } }
From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java
/** * Fetches the supplied user.//from w ww. ja va 2 s . c o m * * @param attrValue the user id * @return the user id for the supplied uid * @throws NamingException LDAP error obtaining user information. */ protected String selectUser(String attrId, String attrValue) throws NamingException { String uidValue = null; InitialLdapContext ctx = createLdapInitialContext(); String uidAttrName = this.getPrincipalUidAttributeID(); String usersCtxDN = this.getUsersCtxDN(); try { // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr); // This gives more control over search behavior : NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + attrId + "=" + attrValue + "))", getSearchControls()); while (answer.hasMore()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); Attribute uidAttr = attrs.get(uidAttrName); if (uidAttr == null) { logger.warn("Invalid user attrValue attribute '" + uidAttrName + "'"); continue; } uidValue = uidAttr.get().toString(); if (uidValue != null) { if (logger.isDebugEnabled()) logger.debug( "Found user '" + uidAttrName + "=" + uidValue + "' for user '" + attrValue + "'"); } else { if (logger.isDebugEnabled()) logger.debug("User not found for user '" + attrValue + "'"); } } } catch (NamingException e) { if (logger.isDebugEnabled()) logger.debug("Failed to locate user", e); } finally { // Close the context to release the connection ctx.close(); } return uidValue; }
From source file:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java
public Set<OIDs> getAllSubOrgIds(boolean pLicensedOrgs, OIDs pOIDs, int pScopy, AasPrincipal pPerformer) throws ExecutionException { Set<OIDs> vSetOIDs = new HashSet<OIDs>(); NamingEnumeration<SearchResult> searchResults = null; try {/*w w w . ja v a 2 s. c o m*/ searchResults = getAllSubOrgs(pLicensedOrgs, pOIDs, pScopy, new String[] { Constants.ldap_ddbOrg_Id, Constants.ldap_ddbOrg_PID, "+" }, pPerformer); SearchResult sr; Attribute attr; while (searchResults.hasMore()) { sr = searchResults.next(); if ((attr = sr.getAttributes().get(Constants.ldap_ddb_EntryDN)) != null) { vSetOIDs.add(new OIDs(String.valueOf(attr.get()), (attr = sr.getAttributes().get(Constants.ldap_ddbOrg_PID)) != null ? String.valueOf(attr.get()) : null)); } else { throw new ExecutionException("entryDN = null : OIDs = " + pOIDs, null); } } } catch (IllegalAccessException ex) { LOG.log(Level.SEVERE, "Connection-Error", ex); throw new ExecutionException(ex.getMessage(), ex.getCause()); } catch (NamingException ne) { LOG.log(Level.SEVERE, "NamingException", ne); throw new ExecutionException(ne.getMessage(), ne.getCause()); } finally { if (searchResults != null) { try { searchResults.close(); searchResults = null; } catch (NamingException ex) { } } } return vSetOIDs; }
From source file:org.olat.ldap.LDAPLoginManagerImpl.java
/** * Creates list of all OLAT Users which have been deleted out of the LDAP directory but still exits in OLAT Configuration: Required Attributes = olatextconfig.xml * (property=reqAttrs) LDAP Base = olatextconfig.xml (property=ldapBase) * /* w w w .j a v a2s .co m*/ * @param syncTime The time to search in LDAP for changes since this time. SyncTime has to formatted: JJJJMMddHHmm * @param ctx The LDAP system connection, if NULL or closed NamingExecpiton is thrown * @return Returns list of Identity from the user which have been deleted in LDAP * @throws NamingException */ public List<Identity> getIdentitysDeletedInLdap(final LdapContext ctx) { if (ctx == null) { return null; } // Find all LDAP Users final String userID = LDAPLoginModule.mapOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER); final String objctClass = LDAPLoginModule.getLdapUserObjectClass(); final List<String> ldapList = new ArrayList<String>(); searchInLdap(new LdapVisitor() { public void visit(final SearchResult result) throws NamingException { final Attributes attrs = result.getAttributes(); final NamingEnumeration<? extends Attribute> aEnum = attrs.getAll(); while (aEnum.hasMore()) { final Attribute attr = aEnum.next(); // use lowercase username ldapList.add(attr.get().toString().toLowerCase()); } } }, "(objectClass=" + objctClass + ")", new String[] { userID }, ctx); if (ldapList.isEmpty()) { logWarn("No users in LDAP found, can't create deletionList!!", null); return null; } // Find all User in OLAT, members of LDAPSecurityGroup final SecurityGroup ldapGroup = securityManager.findSecurityGroupByName(LDAPConstants.SECURITY_GROUP_LDAP); if (ldapGroup == null) { logError("Error getting users from OLAT security group '" + LDAPConstants.SECURITY_GROUP_LDAP + "' : group does not exist", null); return null; } final List<Identity> identityListToDelete = new ArrayList<Identity>(); final List<Identity> olatListIdentity = securityManager.getIdentitiesOfSecurityGroup(ldapGroup); for (final Identity ida : olatListIdentity) { // compare usernames with lowercase if (!ldapList.contains(ida.getName().toLowerCase())) { identityListToDelete.add(ida); } } return identityListToDelete; }