List of usage examples for javax.naming.directory SearchResult getNameInNamespace
public String getNameInNamespace()
From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java
public Collection<NodeDescription> getGroups(Date modifiedSince) { // Work out whether the user and group trees are disjoint. This may allow us to optimize reverse DN // resolution. final LdapName groupDistinguishedNamePrefix; try {//from w ww. j a v a 2s. c om groupDistinguishedNamePrefix = fixedLdapName(this.groupSearchBase.toLowerCase()); } catch (InvalidNameException e) { Object[] params = { this.groupSearchBase.toLowerCase(), e.getLocalizedMessage() }; throw new AlfrescoRuntimeException("synchronization.err.ldap.search.base.invalid", params, e); } final LdapName userDistinguishedNamePrefix; try { userDistinguishedNamePrefix = fixedLdapName(this.userSearchBase.toLowerCase()); } catch (InvalidNameException e) { Object[] params = { this.userSearchBase.toLowerCase(), e.getLocalizedMessage() }; throw new AlfrescoRuntimeException("synchronization.err.ldap.search.base.invalid", params, e); } final boolean disjoint = !groupDistinguishedNamePrefix.startsWith(userDistinguishedNamePrefix) && !userDistinguishedNamePrefix.startsWith(groupDistinguishedNamePrefix); // Choose / generate the query String query; if (modifiedSince == null) { query = this.groupQuery; } else { query = MessageFormat.format(this.groupDifferentialQuery, this.timestampFormat.format(modifiedSince)); } // Run the query and process the results final Map<String, NodeDescription> lookup = new TreeMap<String, NodeDescription>(); processQuery(new AbstractSearchCallback() { // We get a whole new context to avoid interference with cookies from paged results private DirContext ctx = LDAPUserRegistry.this.ldapInitialContextFactory.getDefaultIntialDirContext(); protected void doProcess(SearchResult result) throws NamingException, ParseException { Attributes attributes = result.getAttributes(); Attribute gidAttribute = attributes.get(LDAPUserRegistry.this.groupIdAttributeName); if (gidAttribute == null) { if (LDAPUserRegistry.this.errorOnMissingGID) { Object[] params = { result.getNameInNamespace(), LDAPUserRegistry.this.groupIdAttributeName }; throw new AlfrescoRuntimeException("synchronization.err.ldap.get.group.id.missing", params); } else { LDAPUserRegistry.logger.warn("Missing GID on " + attributes); return; } } String groupShortName = gidAttribute.get(0).toString(); String gid = "GROUP_" + groupShortName; NodeDescription group = lookup.get(gid); if (group == null) { // Apply the mapped properties to the node description group = mapToNode(LDAPUserRegistry.this.groupAttributeMapping, LDAPUserRegistry.this.groupAttributeDefaults, result); // Make sure the "GROUP_" prefix is applied group.getProperties().put(ContentModel.PROP_AUTHORITY_NAME, gid); lookup.put(gid, group); } else if (LDAPUserRegistry.this.errorOnDuplicateGID) { throw new AlfrescoRuntimeException("Duplicate group id found for " + gid); } else { LDAPUserRegistry.logger.warn("Duplicate gid found for " + gid + " -> merging definitions"); } Set<String> childAssocs = group.getChildAssociations(); // Get the repeating (and possibly range restricted) member attribute Attribute memAttribute = getRangeRestrictedAttribute(attributes, LDAPUserRegistry.this.memberAttributeName); int nextStart = LDAPUserRegistry.this.attributeBatchSize; if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger .debug("Processing group: " + gid + ", from source: " + group.getSourceId()); } // Loop until we get to the end of the range while (memAttribute != null) { for (int i = 0; i < memAttribute.size(); i++) { String attribute = (String) memAttribute.get(i); if (attribute != null && attribute.length() > 0) { try { // Attempt to parse the member attribute as a DN. If this fails we have a fallback // in the catch block LdapName distinguishedNameForComparison = fixedLdapName(attribute.toLowerCase()); Attribute nameAttribute; // If the user and group search bases are different we may be able to recognize user // and group DNs without a secondary lookup if (disjoint) { LdapName distinguishedName = fixedLdapName(attribute); Attributes nameAttributes = distinguishedName .getRdn(distinguishedName.size() - 1).toAttributes(); // Recognize user DNs if (distinguishedNameForComparison.startsWith(userDistinguishedNamePrefix) && (nameAttribute = nameAttributes .get(LDAPUserRegistry.this.userIdAttributeName)) != null) { if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger .debug("User DN recognized: " + nameAttribute.get()); } childAssocs.add((String) nameAttribute.get()); continue; } // Recognize group DNs if (distinguishedNameForComparison.startsWith(groupDistinguishedNamePrefix) && (nameAttribute = nameAttributes .get(LDAPUserRegistry.this.groupIdAttributeName)) != null) { if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger.debug( "Group DN recognized: " + "GROUP_" + nameAttribute.get()); } childAssocs.add("GROUP_" + nameAttribute.get()); continue; } } // If we can't determine the name and type from the DN alone, try a directory lookup if (distinguishedNameForComparison.startsWith(userDistinguishedNamePrefix) || distinguishedNameForComparison .startsWith(groupDistinguishedNamePrefix)) { try { Attributes childAttributes = this.ctx.getAttributes(jndiName(attribute), new String[] { "objectclass", LDAPUserRegistry.this.groupIdAttributeName, LDAPUserRegistry.this.userIdAttributeName }); Attribute objectClass = childAttributes.get("objectclass"); if (hasAttributeValue(objectClass, LDAPUserRegistry.this.personType)) { nameAttribute = childAttributes .get(LDAPUserRegistry.this.userIdAttributeName); if (nameAttribute == null) { if (LDAPUserRegistry.this.errorOnMissingUID) { throw new AlfrescoRuntimeException( "User missing user id attribute DN =" + attribute + " att = " + LDAPUserRegistry.this.userIdAttributeName); } else { LDAPUserRegistry.logger .warn("User missing user id attribute DN =" + attribute + " att = " + LDAPUserRegistry.this.userIdAttributeName); continue; } } if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger .debug("User DN recognized by directory lookup: " + nameAttribute.get()); } childAssocs.add((String) nameAttribute.get()); continue; } else if (hasAttributeValue(objectClass, LDAPUserRegistry.this.groupType)) { nameAttribute = childAttributes .get(LDAPUserRegistry.this.groupIdAttributeName); if (nameAttribute == null) { if (LDAPUserRegistry.this.errorOnMissingGID) { Object[] params = { result.getNameInNamespace(), LDAPUserRegistry.this.groupIdAttributeName }; throw new AlfrescoRuntimeException( "synchronization.err.ldap.get.group.id.missing", params); } else { LDAPUserRegistry.logger .warn("Missing GID on " + childAttributes); continue; } } if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger .debug("Group DN recognized by directory lookup: " + "GROUP_" + nameAttribute.get()); } childAssocs.add("GROUP_" + nameAttribute.get()); continue; } } catch (NamingException e) { // Unresolvable name if (LDAPUserRegistry.this.errorOnMissingMembers) { Object[] params = { groupShortName, attribute, e.getLocalizedMessage() }; throw new AlfrescoRuntimeException( "synchronization.err.ldap.group.member.missing.exception", params, e); } LDAPUserRegistry.logger.warn("Failed to resolve member of group '" + groupShortName + "' with distinguished name: " + attribute, e); continue; } } if (LDAPUserRegistry.this.errorOnMissingMembers) { Object[] params = { groupShortName, attribute }; throw new AlfrescoRuntimeException( "synchronization.err.ldap.group.member.missing", params); } LDAPUserRegistry.logger.warn("Failed to resolve member of group '" + groupShortName + "' with distinguished name: " + attribute); } catch (InvalidNameException e) { // The member attribute didn't parse as a DN. So assume we have a group class like // posixGroup (FDS) that directly lists user names if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger .debug("Member DN recognized as posixGroup: " + attribute); } childAssocs.add(attribute); } } } // If we are using attribute matching and we haven't got to the end (indicated by an asterisk), // fetch the next batch if (nextStart > 0 && !LDAPUserRegistry.PATTERN_RANGE_END .matcher(memAttribute.getID().toLowerCase()).find()) { Attributes childAttributes = this.ctx.getAttributes(jndiName(result.getNameInNamespace()), new String[] { LDAPUserRegistry.this.memberAttributeName + ";range=" + nextStart + '-' + (nextStart + LDAPUserRegistry.this.attributeBatchSize - 1) }); memAttribute = getRangeRestrictedAttribute(childAttributes, LDAPUserRegistry.this.memberAttributeName); nextStart += LDAPUserRegistry.this.attributeBatchSize; } else { memAttribute = null; } } } public void close() throws NamingException { this.ctx.close(); } }, this.groupSearchBase, query, this.groupKeys.getFirst()); if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger.debug("Found " + lookup.size()); } return lookup.values(); }
From source file:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java
/** * Searches the remote directory for the user's entry and returns its distinguished name * string./* w ww . j av a 2 s .c o m*/ * * @param userId * the ID of the user whose DN is to be retrieved * @param context * the directory context from which to retrieve the user's DN * @return String * @throws NamingException */ protected String findUserDn(String userId, DirContext context) throws NamingException { String userDn = null; for (MessageFormat userSearchPattern : userSearchPatterns) { try { String searchFilter = userSearchPattern.format(new String[] { userId }); SearchControls constraints = new SearchControls(); constraints.setSearchScope( searchUserSubtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE); constraints.setTimeLimit(userSearchTimeout); NamingEnumeration<SearchResult> results = context.search(userSearchBase, searchFilter, constraints); SearchResult result = null; try { if ((results != null) && results.hasMore()) { result = results.next(); // Make sure only one entry exists for the requested user if (results.hasMore()) { log.warn("Multiple entries found for user: " + userId); result = null; } } } catch (PartialResultException e) { // Ignore partial result errors - most likely due to ActiveDirectory referrals } if (result != null) { userDn = result.getNameInNamespace(); break; } } catch (NameNotFoundException e) { // Ignore and keep searching } } return userDn; }
From source file:de.tuttas.util.LDAPUtil.java
/** * Benutzer aus der LDAP Abfragen/*from ww w . ja va 2s.c o m*/ * * @param username Benutzername * @param password Kennwort * @return der Benutzer * @throws Exception Wenn etwas schief ging */ public LDAPUser authenticateJndi(String username, String password) throws Exception { // Anbindung ans LDAP Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.PROVIDER_URL, Config.getInstance().ldaphost); props.put(Context.SECURITY_PRINCIPAL, Config.getInstance().bindUser);//adminuser - User with special priviledge, dn user props.put(Context.SECURITY_CREDENTIALS, Config.getInstance().bindPassword);//dn user password try { context = new InitialDirContext(props); ctrls = new SearchControls(); ctrls.setReturningAttributes(new String[] { "description", "mail", "sn", "initials", "givenName", "memberOf", "userPrincipalName", "distinguishedName" }); ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE); } catch (NamingException ex) { Logger.getLogger(LDAPUtil.class.getName()).log(Level.SEVERE, null, ex); } NamingEnumeration<javax.naming.directory.SearchResult> answers = context .search(Config.getInstance().userContext, "(cn=" + username + ")", ctrls); Log.d("answers=" + answers); Log.d("answers=" + answers.hasMore()); if (!answers.hasMore()) { return null; } javax.naming.directory.SearchResult result = answers.nextElement(); try { for (NamingEnumeration ae = result.getAttributes().getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); Log.d("attribute: " + attr.getID()); /* print each value */ for (NamingEnumeration e = attr.getAll(); e.hasMore(); System.out.println("value: " + e.next())) ; } } catch (NamingException e) { e.printStackTrace(); } String inititials = ""; if (result.getAttributes().get("initials") != null) { inititials = result.getAttributes().get("initials").getAll().next().toString(); } LDAPUser u; if (result.getAttributes().get("mail") == null) { u = new LDAPUser(result.getAttributes().get("sn").getAll().next().toString(), result.getAttributes().get("givenName").getAll().next().toString(), "", inititials); } else { u = new LDAPUser(result.getAttributes().get("sn").getAll().next().toString(), result.getAttributes().get("givenName").getAll().next().toString(), result.getAttributes().get("mail").getAll().next().toString(), inititials); } String dName = result.getAttributes().get("distinguishedName").getAll().next().toString(); Log.d("dName=" + dName); if (dName.contains("OU=Lehrer")) { Log.d("Ich bin ein Lehrer"); u.setRole(Roles.toString(Roles.LEHRER)); } else { Log.d("Ich bin ein Schler"); u.setRole(Roles.toString(Roles.SCHUELER)); if (result.getAttributes().get("memberOf") != null) { String memberOf = result.getAttributes().get("memberOf").getAll().next().toString(); String courseName = memberOf.split(",")[0]; courseName = courseName.substring(courseName.indexOf("=") + 1); Log.d("Name der Klasse ist " + courseName); u.setCourse(courseName); } } String user = result.getNameInNamespace(); try { props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.PROVIDER_URL, Config.getInstance().ldaphost); props.put(Context.SECURITY_PRINCIPAL, user); props.put(Context.SECURITY_CREDENTIALS, password); context = new InitialDirContext(props); } catch (Exception e) { return null; } return u; }
From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java
/** * Remove existing statically defined links for the given target id (dynamic references remain unaltered) * * @see org.nuxeo.ecm.directory.Reference#removeLinksForTarget(String) *//*from w w w .java2 s . c o m*/ @Override public void removeLinksForTarget(String targetId) throws DirectoryException { if (!isStatic()) { // nothing to do: dynamic references cannot be updated return; } LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory(); LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory(); String attributeId = getStaticAttributeId(); try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession(); LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) { if (!sourceSession.isReadOnly()) { // get the dn of the target that matches targetId String targetAttributeValue; if (staticAttributeIdIsDn) { SearchResult targetLdapEntry = targetSession.getLdapEntry(targetId); if (targetLdapEntry == null) { String rdnAttribute = ldapTargetDirectory.getDescriptor().getRdnAttribute(); if (!rdnAttribute.equals(targetSession.idAttribute)) { log.warn(String.format( "cannot remove links to missing entry %s in directory %s for reference %s", targetId, ldapTargetDirectory.getName(), this)); return; } // the entry might have already been deleted, try to // re-forge it if possible (might not work if scope is // subtree) targetAttributeValue = String.format("%s=%s,%s", rdnAttribute, targetId, ldapTargetDirectory.getDescriptor().getSearchBaseDn()); } else { targetAttributeValue = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace()); } } else { targetAttributeValue = targetId; } // build a LDAP query to find entries that point to the target String searchFilter = String.format("(%s=%s)", attributeId, targetAttributeValue); String sourceFilter = ldapSourceDirectory.getBaseFilter(); if (sourceFilter != null && !"".equals(sourceFilter)) { searchFilter = String.format("(&(%s)(%s))", searchFilter, sourceFilter); } SearchControls scts = new SearchControls(); scts.setSearchScope(ldapSourceDirectory.getDescriptor().getSearchScope()); scts.setReturningAttributes(new String[] { attributeId }); // find all source entries that point to the target key and // clean // those references if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.removeLinksForTarget(%s): LDAP search baseDn='%s' " + " filter='%s' scope='%s' [%s]", targetId, sourceSession.searchBaseDn, searchFilter, scts.getSearchScope(), this)); } NamingEnumeration<SearchResult> results = sourceSession.dirContext .search(sourceSession.searchBaseDn, searchFilter, scts); String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker(); Attributes emptyAttribute = new BasicAttributes(attributeId, emptyRefMarker); try { while (results.hasMore()) { SearchResult result = results.next(); Attributes attrs = result.getAttributes(); Attribute attr = attrs.get(attributeId); try { if (attr.size() == 1) { // the attribute holds the last reference, put // the // empty ref. marker before removing the // attribute // since empty attribute are often not allowed // by // the server schema if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' " + "mod_op='ADD_ATTRIBUTE' attrs='%s' [%s]", targetId, result.getNameInNamespace(), attrs, this)); } sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(), DirContext.ADD_ATTRIBUTE, emptyAttribute); } // remove the reference to the target key attrs = new BasicAttributes(); attr = new BasicAttribute(attributeId); attr.add(targetAttributeValue); attrs.put(attr); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' " + "mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]", targetId, result.getNameInNamespace(), attrs, this)); } sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(), DirContext.REMOVE_ATTRIBUTE, attrs); } catch (SchemaViolationException e) { if (isDynamic()) { // we are editing an entry that has no static // part log.warn(String.format("cannot remove dynamic reference in field %s for target %s", getFieldName(), targetId)); } else { // this is a real schema configuration problem, // wrapup the exception throw new DirectoryException(e); } } } } finally { results.close(); } } } catch (NamingException e) { throw new DirectoryException("removeLinksForTarget failed: " + e.getMessage(), e); } }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * @param userName Username of the user. * @param searchBase Searchbase which the user should be searched for. * @param searchFilter Search filter of the username. * @return DN of the user whose usename is given. * @throws UserStoreException If an error occurs while connecting to the LDAP userstore. *//*from w ww. j a va2 s . c o m*/ private String getNameInSpaceForUserName(String userName, String searchBase, String searchFilter) throws UserStoreException { boolean debug = log.isDebugEnabled(); String userDN = null; DirContext dirContext = this.connectionSource.getContext(); NamingEnumeration<SearchResult> answer = null; try { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); if (log.isDebugEnabled()) { try { log.debug("Searching for user with SearchFilter: " + searchFilter + " in SearchBase: " + dirContext.getNameInNamespace()); } catch (NamingException e) { log.debug("Error while getting DN of search base", e); } } SearchResult userObj; String[] searchBases = searchBase.split(CommonConstants.XML_PATTERN_SEPERATOR); for (String base : searchBases) { answer = dirContext.search(escapeDNForSearch(base), searchFilter, searchCtls); if (answer.hasMore()) { userObj = answer.next(); if (userObj != null) { //no need to decode since , if decoded the whole string, can't be encoded again //eg CN=Hello\,Ok=test\,test, OU=Industry userDN = userObj.getNameInNamespace(); break; } } } if (debug) { log.debug("Name in space for " + userName + " is " + userDN); } } catch (Exception e) { log.debug(e.getMessage(), e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } return userDN; }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
protected void addLDAPRole(RoleContext context) throws UserStoreException { String roleName = context.getRoleName(); String[] userList = context.getMembers(); String groupEntryObjectClass = ((LDAPRoleContext) context).getGroupEntryObjectClass(); String groupNameAttribute = ((LDAPRoleContext) context).getRoleNameProperty(); String searchBase = ((LDAPRoleContext) context).getSearchBase(); if ((userList == null || userList.length == 0) && !emptyRolesAllowed) { String errorMessage = "Can not create empty role. There should be at least " + "one user for the role."; throw new UserStoreException(errorMessage); } else if (userList == null && emptyRolesAllowed || userList != null && userList.length > 0 && !emptyRolesAllowed || emptyRolesAllowed) { // if (userList.length > 0) { DirContext mainDirContext = this.connectionSource.getContext(); DirContext groupContext = null; NamingEnumeration<SearchResult> results = null; try {//from w w w.j a va2 s . co m // create the attribute set for group entry Attributes groupAttributes = new BasicAttributes(true); // create group entry's object class attribute Attribute objectClassAttribute = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME); objectClassAttribute.add(groupEntryObjectClass); groupAttributes.put(objectClassAttribute); // create cn attribute Attribute cnAttribute = new BasicAttribute(groupNameAttribute); cnAttribute.add(roleName); groupAttributes.put(cnAttribute); // following check is for if emptyRolesAllowed made this // code executed. if (userList != null && userList.length > 0) { String memberAttributeName = realmConfig .getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE); Attribute memberAttribute = new BasicAttribute(memberAttributeName); for (String userName : userList) { if (userName == null || userName.trim().length() == 0) { continue; } // search the user in user search base String searchFilter = realmConfig .getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); results = searchInUserBase(searchFilter, new String[] {}, SearchControls.SUBTREE_SCOPE, mainDirContext); // we assume only one user with the given user // name under user search base. SearchResult userResult = null; if (results.hasMore()) { userResult = results.next(); } else { String errorMsg = "There is no user with the user name: " + userName + " to be added to this role."; logger.error(errorMsg); throw new UserStoreException(errorMsg); } // get his DN String userEntryDN = userResult.getNameInNamespace(); // put it as member-attribute value memberAttribute.add(userEntryDN); } groupAttributes.put(memberAttribute); } groupContext = (DirContext) mainDirContext.lookup(searchBase); NameParser ldapParser = groupContext.getNameParser(""); /* * Name compoundGroupName = ldapParser.parse(groupNameAttributeName + "=" + * roleName); */ Name compoundGroupName = ldapParser.parse("cn=" + roleName); groupContext.bind(compoundGroupName, null, groupAttributes); } catch (NamingException e) { String errorMsg = "Role: " + roleName + " could not be added."; if (log.isDebugEnabled()) { log.debug(errorMsg, e); } throw new UserStoreException(errorMsg, e); } catch (Exception e) { String errorMsg = "Role: " + roleName + " could not be added."; if (log.isDebugEnabled()) { log.debug(errorMsg, e); } throw new UserStoreException(errorMsg, e); } finally { JNDIUtil.closeNamingEnumeration(results); JNDIUtil.closeContext(groupContext); JNDIUtil.closeContext(mainDirContext); } } }
From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java
/** * Fetch both statically and dynamically defined references and merge the results. * * @see org.nuxeo.ecm.directory.Reference#getSourceIdsForTarget(String) *//*from w ww.j av a2 s.com*/ @Override public List<String> getSourceIdsForTarget(String targetId) throws DirectoryException { // container to hold merged references Set<String> sourceIds = new TreeSet<>(); SearchResult targetLdapEntry = null; String targetDn = null; // step #1: resolve static references String staticAttributeId = getStaticAttributeId(); if (staticAttributeId != null) { // step #1.1: fetch the dn of the targetId entry in the target // directory by the static dn valued strategy LDAPDirectory targetDir = getTargetLDAPDirectory(); if (staticAttributeIdIsDn) { try (LDAPSession targetSession = (LDAPSession) targetDir.getSession()) { targetLdapEntry = targetSession.getLdapEntry(targetId, false); if (targetLdapEntry == null) { String msg = String.format( "Failed to perform inverse lookup on LDAPReference" + " resolving field '%s' of '%s' to entries of '%s'" + " using the static content of attribute '%s':" + " entry '%s' cannot be found in '%s'", fieldName, sourceDirectory, targetDirectoryName, staticAttributeId, targetId, targetDirectoryName); throw new DirectoryEntryNotFoundException(msg); } targetDn = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace()); } catch (NamingException e) { throw new DirectoryException( "error fetching " + targetId + " from " + targetDirectoryName + ": " + e.getMessage(), e); } } // step #1.2: search for entries that reference that dn in the // source directory and collect their ids LDAPDirectory ldapSourceDirectory = getSourceLDAPDirectory(); String filterExpr = String.format("(&(%s={0})%s)", staticAttributeId, ldapSourceDirectory.getBaseFilter()); String[] filterArgs = new String[1]; if (staticAttributeIdIsDn) { filterArgs[0] = targetDn; } else { filterArgs[0] = targetId; } String searchBaseDn = ldapSourceDirectory.getDescriptor().getSearchBaseDn(); SearchControls sctls = ldapSourceDirectory.getSearchControls(); try (LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) { if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.getSourceIdsForTarget(%s): LDAP search search base='%s'" + " filter='%s' args='%s' scope='%s' [%s]", targetId, searchBaseDn, filterExpr, StringUtils.join(filterArgs, ", "), sctls.getSearchScope(), this)); } NamingEnumeration<SearchResult> results = sourceSession.dirContext.search(searchBaseDn, filterExpr, filterArgs, sctls); try { while (results.hasMore()) { Attributes attributes = results.next().getAttributes(); // NXP-2461: check that id field is filled Attribute attr = attributes.get(sourceSession.idAttribute); if (attr != null) { Object value = attr.get(); if (value != null) { sourceIds.add(value.toString()); } } } } finally { results.close(); } } catch (NamingException e) { throw new DirectoryException("error during reference search for " + filterArgs[0], e); } } // step #2: resolve dynamic references String dynamicAttributeId = this.dynamicAttributeId; if (dynamicAttributeId != null) { LDAPDirectory ldapSourceDirectory = getSourceLDAPDirectory(); LDAPDirectory ldapTargetDirectory = getTargetLDAPDirectory(); String searchBaseDn = ldapSourceDirectory.getDescriptor().getSearchBaseDn(); try (LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession(); LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession()) { // step #2.1: fetch the target entry to apply the ldap url // filters of the candidate sources on it if (targetLdapEntry == null) { // only fetch the entry if not already fetched by the // static // attributes references resolution targetLdapEntry = targetSession.getLdapEntry(targetId, false); } if (targetLdapEntry == null) { String msg = String.format( "Failed to perform inverse lookup on LDAPReference" + " resolving field '%s' of '%s' to entries of '%s'" + " using the dynamic content of attribute '%s':" + " entry '%s' cannot be found in '%s'", fieldName, ldapSourceDirectory, targetDirectoryName, dynamicAttributeId, targetId, targetDirectoryName); throw new DirectoryException(msg); } targetDn = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace()); Attributes targetAttributes = targetLdapEntry.getAttributes(); // step #2.2: find the list of entries that hold candidate // dynamic links in the source directory SearchControls sctls = ldapSourceDirectory.getSearchControls(); sctls.setReturningAttributes(new String[] { sourceSession.idAttribute, dynamicAttributeId }); String filterExpr = String.format("%s=*", dynamicAttributeId); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.getSourceIdsForTarget(%s): LDAP search search base='%s'" + " filter='%s' scope='%s' [%s]", targetId, searchBaseDn, filterExpr, sctls.getSearchScope(), this)); } NamingEnumeration<SearchResult> results = sourceSession.dirContext.search(searchBaseDn, filterExpr, sctls); try { while (results.hasMore()) { // step #2.3: for each sourceId and each ldapUrl test // whether the current target entry matches the // collected // URL Attributes sourceAttributes = results.next().getAttributes(); NamingEnumeration<?> ldapUrls = sourceAttributes.get(dynamicAttributeId).getAll(); try { while (ldapUrls.hasMore()) { LdapURL ldapUrl = new LdapURL(ldapUrls.next().toString()); String candidateDN = pseudoNormalizeDn(ldapUrl.getDN()); // check base URL if (!targetDn.endsWith(candidateDN)) { continue; } // check onelevel scope constraints if ("onelevel".equals(ldapUrl.getScope())) { int targetDnSize = new LdapName(targetDn).size(); int urlDnSize = new LdapName(candidateDN).size(); if (targetDnSize - urlDnSize > 1) { // target is not a direct child of the // DN of the // LDAP URL continue; } } // check that the target entry matches the // filter if (getFilterMatcher().match(targetAttributes, ldapUrl.getFilter())) { // the target match the source url, add it // to the // collected ids sourceIds.add(sourceAttributes.get(sourceSession.idAttribute).get().toString()); } } } finally { ldapUrls.close(); } } } finally { results.close(); } } catch (NamingException e) { throw new DirectoryException("error during reference search for " + targetId, e); } } /* * This kind of reference is not supported because Active Directory use filter expression not yet supported by * LDAPFilterMatcher. See NXP-4562 */ if (dynamicReferences != null && dynamicReferences.length > 0) { log.error("This kind of reference is not supported."); } return new ArrayList<>(sourceIds); }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * Check whether this is the last/only user in this group. * * @param userDN DN of the User./*from w w w . j a v a 2 s . c o m*/ * @param groupEntry SearchResult Representing the Group. * @return true if user is the only one in role, false otherwise. */ protected boolean isOnlyUserInRole(String userDN, SearchResult groupEntry) throws UserStoreException { boolean isOnlyUserInRole = false; try { Attributes groupAttributes = groupEntry.getAttributes(); if (groupAttributes != null) { NamingEnumeration attributes = groupAttributes.getAll(); while (attributes.hasMoreElements()) { Attribute memberAttribute = (Attribute) attributes.next(); String memberAttributeName = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE); String attributeID = memberAttribute.getID(); if (memberAttributeName.equals(attributeID)) { if (memberAttribute.size() == 1 && userDN.equals(memberAttribute.get())) { return true; } } } attributes.close(); } } catch (NamingException e) { String errorMessage = "Error occurred while looping through attributes set of group: " + groupEntry.getNameInNamespace(); if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } return isOnlyUserInRole; }
From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java
/** * * {@inheritDoc}//from w ww.j ava 2 s.com */ @Override public String resolveDistinguishedName(final String userId, final AuthenticationDiagnostic diagnostic) throws AuthenticationException { LOGGER.debug("resolveDistinguishedName userId: {}", userId); final SearchControls userSearchCtls = new SearchControls(); userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868 userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName }); final String query = this.userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName + "= userId))"; NamingEnumeration<SearchResult> searchResults = null; SearchResult result = null; InitialDirContext ctx = null; try { ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic); // Execute the user query with an additional condition that ensures only the user with the required ID is // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation searchResults = ctx.search(this.userSearchBase, "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId }, userSearchCtls); if (searchResults.hasMore()) { result = searchResults.next(); final Attributes attributes = result.getAttributes(); final Attribute uidAttribute = attributes.get(this.userIdAttributeName); if (uidAttribute == null) { if (this.errorOnMissingUID) { throw new AlfrescoRuntimeException( "User returned by user search does not have mandatory user id attribute " + attributes); } else { LOGGER.warn("User returned by user search does not have mandatory user id attribute {}", attributes); } } // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will // only resolve this user if the user ID matches else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) { final String name = result.getNameInNamespace(); this.commonCloseSearchResult(result); result = null; return name; } this.commonCloseSearchResult(result); result = null; } final Object[] args = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_LOOKUP_USER, false, args); throw new AuthenticationException("authentication.err.connection.ldap.user.notfound", args, diagnostic); } catch (final NamingException e) { // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory final Object[] args1 = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1); // failed to search final Object[] args = { e.getLocalizedMessage() }; throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic, args, e); } finally { this.commonAfterQueryCleanup(searchResults, result, ctx); } }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
@SuppressWarnings("rawtypes") @Override/* w w w . j av a 2 s . co m*/ public void doUpdateCredential(String userName, Object newCredential, Object oldCredential) throws UserStoreException { DirContext dirContext = this.connectionSource.getContext(); DirContext subDirContext = null; // first search the existing user entry. String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String searchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(new String[] { "userPassword" }); NamingEnumeration<SearchResult> namingEnumeration = null; NamingEnumeration passwords = null; try { namingEnumeration = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControls); // here we assume only one user // TODO: what to do if there are more than one user SearchResult searchResult = null; String passwordHashMethod = realmConfig.getUserStoreProperty(PASSWORD_HASH_METHOD); while (namingEnumeration.hasMore()) { searchResult = namingEnumeration.next(); String dnName = searchResult.getName(); subDirContext = (DirContext) dirContext.lookup(searchBase); Attribute passwordAttribute = new BasicAttribute("userPassword"); passwordAttribute.add( UserCoreUtil.getPasswordToStore((String) newCredential, passwordHashMethod, kdcEnabled)); BasicAttributes basicAttributes = new BasicAttributes(true); basicAttributes.put(passwordAttribute); subDirContext.modifyAttributes(dnName, DirContext.REPLACE_ATTRIBUTE, basicAttributes); } // we check whether both carbon admin entry and ldap connection // entry are the same if (searchResult.getNameInNamespace() .equals(realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_NAME))) { this.connectionSource.updateCredential((String) newCredential); } } catch (NamingException e) { String errorMessage = "Can not access the directory service for user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(passwords); JNDIUtil.closeNamingEnumeration(namingEnumeration); JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(dirContext); } }