List of usage examples for javax.naming NamingEnumeration next
public T next() throws NamingException;
From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
/** * @param searchBase/*from w w w .j a v a 2s. com*/ * @param searchFilter * @param searchCtls * @param objectSid * @param primaryGroupID * @param userAttributeId * @param groupAttributeName * @return * @throws UserStoreException */ private List<String> getAttributeListOfOneElementWithPrimarGroup(String searchBase, String searchFilter, SearchControls searchCtls, String objectSid, String primaryGroupID, String userAttributeId, String groupAttributeName) throws UserStoreException { boolean debug = log.isDebugEnabled(); List<String> list = new ArrayList<String>(); DirContext dirContext = null; NamingEnumeration<SearchResult> answer = null; if (debug) { log.debug("GetAttributeListOfOneElementWithPrimarGroup. SearchBase: " + searchBase + " SearchFilter: " + searchFilter); } try { dirContext = connectionSource.getContext(); answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls); int count = 0; while (answer.hasMore()) { if (count > 0) { log.error("More than element user exist with name"); throw new UserStoreException("More than element user exist with name"); } SearchResult sr = (SearchResult) answer.next(); count++; list = parseSearchResult(sr, groupAttributeName); String primaryGroupSID = LDAPUtil.getPrimaryGroupSID(sr, objectSid, primaryGroupID); String primaryGroupName = LDAPUtil.findGroupBySID(dirContext, searchBase, primaryGroupSID, userAttributeId); if (primaryGroupName != null) { list.add(primaryGroupName); } } } catch (PartialResultException e) { // can be due to referrals in AD. so just ignore error String errorMessage = "Error occurred while GetAttributeListOfOneElementWithPrimarGroup. SearchBase: " + searchBase + " SearchFilter: " + searchFilter; if (isIgnorePartialResultException()) { if (log.isDebugEnabled()) { log.debug(errorMessage, e); } } else { throw new UserStoreException(errorMessage, e); } } catch (NamingException e) { if (log.isDebugEnabled()) { log.debug(e.getMessage(), e); } throw new UserStoreException(e.getMessage(), e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } if (debug) { log.debug("GetAttributeListOfOneElementWithPrimarGroup. SearchBase: " + searchBase + " SearchFilter: " + searchFilter); Iterator<String> ite = list.iterator(); while (ite.hasNext()) { log.debug("result: " + ite.next()); } } return list; }
From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
@SuppressWarnings("rawtypes") protected List<String> getAttributeListOfOneElement(String searchBases, String searchFilter, SearchControls searchCtls) throws UserStoreException { List<String> list = new ArrayList<String>(); DirContext dirContext = null; NamingEnumeration<SearchResult> answer = null; try {/* ww w. ja va 2s. c o m*/ dirContext = connectionSource.getContext(); // handle multiple search bases String[] searchBaseArray = searchBases.split("#"); for (String searchBase : searchBaseArray) { try { answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls); int count = 0; if (answer.hasMore()) { while (answer.hasMore()) { if (count > 0) { log.error("More than element user exist with name"); throw new UserStoreException("More than element user exist with name"); } SearchResult sr = (SearchResult) answer.next(); count++; list = parseSearchResult(sr, null); } break; } } catch (NamingException e) { //ignore if (log.isDebugEnabled()) { log.debug(e); } } } } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } return list; }
From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
/** * @param userName//w w w. j a v a 2s.c o m * @param searchBase * @param searchFilter * @return * @throws UserStoreException */ protected 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 = null; String[] searchBases = searchBase.split("#"); for (String base : searchBases) { answer = dirContext.search(escapeDNForSearch(base), searchFilter, searchCtls); if (answer.hasMore()) { userObj = (SearchResult) 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 (userDN != null) { LdapName ldn = new LdapName(userDN); userCache.put(userName, ldn); } 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.ReadOnlyLDAPUserStoreManager.java
/** * @param searchBases/*from w w w . j a v a 2 s.c o m*/ * @param searchFilter * @param searchCtls * @param property * @return * @throws UserStoreException */ private List<String> getListOfNames(String searchBases, String searchFilter, SearchControls searchCtls, String property, boolean appendDn) throws UserStoreException { searchFilter = searchFilter.replace("*", "\\*"); boolean debug = log.isDebugEnabled(); List<String> names = new ArrayList<String>(); DirContext dirContext = null; NamingEnumeration<SearchResult> answer = null; if (debug) { log.debug("Result for searchBase: " + searchBases + " searchFilter: " + searchFilter + " property:" + property + " appendDN: " + appendDn); } try { dirContext = connectionSource.getContext(); // handle multiple search bases String[] searchBaseArray = searchBases.split("#"); for (String searchBase : searchBaseArray) { try { answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls); String domain = this.getRealmConfiguration() .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); if (sr.getAttributes() != null) { Attribute attr = sr.getAttributes().get(property); if (attr != null) { for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) { String name = (String) vals.nextElement(); if (debug) { log.debug("Found user: " + name); } names.add(name); } } } } } catch (NamingException e) { // ignore if (log.isDebugEnabled()) { log.debug(e); } } if (debug) { for (String name : names) { log.debug("Result : " + name); } } } return names; } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } }
From source file:no.feide.moria.directory.backend.JNDIBackend.java
/** * Does a subtree search for an element given a pattern. Only the first * element found is considered, and all references are searched in order * until either a match is found or no more references are left to search. * @param ldap/*from w w w . j av a2 s.co m*/ * A prepared LDAP context. * @param pattern * The search pattern. Must not include the character '*' or the * substring '\2a' to prevent possible LDAP exploits. * @return The element's relative DN, or <code>null</code> if none was * found. <code>null</code> is also returned if the search pattern * contains an illegal character or substring. * @throws BackendException * If there was a problem accessing the backend. Typical causes * include timeouts. */ private String ldapSearch(final InitialLdapContext ldap, final String pattern) throws BackendException { // Check pattern for illegal content. String[] illegals = { "*", "\\2a" }; for (int i = 0; i < illegals.length; i++) { if (pattern.indexOf(illegals[i]) > -1) return null; } // The context provider URL, for later logging. String url = "unknown backend"; // Start counting the (milli)seconds and prepare for timeouts. long searchStart = System.currentTimeMillis(); JNDISearchInterruptor interruptTask = new JNDISearchInterruptor(ldap, mySessionTicket); NamingEnumeration results; try { // Remember the URL, for later logging. url = (String) ldap.getEnvironment().get(Context.PROVIDER_URL); interruptTask.setURL(url); // Start timeout interruptor and perform the search. Timer interruptTimer = new Timer(); interruptTimer.schedule(interruptTask, (1000 * myTimeout)); results = ldap.search("", pattern, new SearchControls(SearchControls.SUBTREE_SCOPE, 0, 1000 * myTimeout, new String[] {}, false, false)); interruptTimer.cancel(); if (!results.hasMore()) return null; } catch (TimeLimitExceededException e) { // The search timed out. log.logWarn("Search on " + url + " for " + pattern + " timed out after ~" + (System.currentTimeMillis() - searchStart) + "ms", mySessionTicket); return null; } catch (SizeLimitExceededException e) { // The search returned too many results. log.logWarn("Search on " + url + " for " + pattern + " returned too many results", mySessionTicket); return null; } catch (NameNotFoundException e) { // Element not found. Possibly non-existing reference. log.logDebug("Could not find " + pattern + " on " + url, mySessionTicket); // Necessary? return null; } catch (AuthenticationException e) { // Search failed authentication; check non-anonymous search config. try { final String searchUser = (String) ldap.getEnvironment().get(Context.SECURITY_PRINCIPAL); final String errorMessage; if ((searchUser == null) || searchUser.equals("")) errorMessage = "Anonymous search failed authentication on " + url; else errorMessage = "Could not authenticate search user " + searchUser + " on " + url; log.logDebug(errorMessage, mySessionTicket); throw new BackendException(errorMessage, e); } catch (NamingException f) { // Should not happen! log.logCritical("Unable to read LDAP environment", mySessionTicket, f); throw new BackendException("Unable to read LDAP environment", f); } } catch (NamingException e) { // Did we interrupt the search ourselves? if (interruptTask.finished()) { final long elapsed = System.currentTimeMillis() - searchStart; log.logWarn("Search on " + url + " for " + pattern + " timed out after ~" + elapsed + "ms", mySessionTicket); throw new BackendException("Search on " + url + " for " + pattern + " timed out after ~" + elapsed + "ms; connection terminated"); } // All other exceptions. log.logWarn("Search on " + url + " for " + pattern + " failed", mySessionTicket, e); return null; } // We just found at least one element. Did we get an ambigious result? SearchResult entry = null; try { entry = (SearchResult) results.next(); String buffer = new String(); while (results.hasMoreElements()) buffer = buffer + ", " + ((SearchResult) results.next()).getName(); if (!buffer.equals("")) log.logWarn("Search on " + url + " for " + pattern + " gave ambiguous result: [" + entry.getName() + buffer + "]", mySessionTicket); // TODO: Throw BackendException, or a subclass, or just (as now) // pick the first and hope for the best? buffer = null; } catch (NamingException e) { throw new BackendException("Unable to read search results", e); } return entry.getName(); // Relative DN (to the reference). }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * {@inheritDoc}/* w w w.j av a 2 s . co m*/ */ @Override public String[] doGetUserListOfRole(String roleName, int maxItemLimit) throws UserStoreException { boolean debug = log.isDebugEnabled(); List<String> userList = new ArrayList<String>(); String[] names = new String[0]; int givenMax = CommonConstants.MAX_USER_ROLE_LIST; int searchTime = CommonConstants.MAX_SEARCH_TIME; try { givenMax = Integer.parseInt(userStoreProperties.get(CommonConstants.PROPERTY_MAX_USER_LIST)); } catch (Exception e) { givenMax = CommonConstants.MAX_USER_ROLE_LIST; } try { searchTime = Integer.parseInt(userStoreProperties.get(CommonConstants.PROPERTY_MAX_SEARCH_TIME)); } catch (Exception e) { searchTime = CommonConstants.MAX_SEARCH_TIME; } if (maxItemLimit <= 0 || maxItemLimit > givenMax) { maxItemLimit = givenMax; } DirContext dirContext = null; NamingEnumeration<SearchResult> answer = null; try { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setTimeLimit(searchTime); searchCtls.setCountLimit(maxItemLimit); String searchFilter = userStoreProperties.get(LDAPConstants.GROUP_NAME_LIST_FILTER); String roleNameProperty = userStoreProperties.get(LDAPConstants.GROUP_NAME_ATTRIBUTE); searchFilter = "(&" + searchFilter + "(" + roleNameProperty + "=" + escapeSpecialCharactersForFilter(roleName) + "))"; String membershipProperty = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE); String returnedAtts[] = { membershipProperty }; searchCtls.setReturningAttributes(returnedAtts); List<String> userDNList = new ArrayList<String>(); SearchResult sr = null; dirContext = connectionSource.getContext(); // handling multiple search bases String searchBases = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE); String[] roleSearchBaseArray = searchBases.split("#"); for (String searchBase : roleSearchBaseArray) { if (debug) { log.debug("Searching role: " + roleName + " SearchBase: " + searchBase + " SearchFilter: " + searchFilter); } try { // read the DN of users who are members of the group answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls); int count = 0; if (answer.hasMore()) { // to check if there is a result while (answer.hasMore()) { // to check if there are more than one group if (count > 0) { throw new UserStoreException("More than one group exist with name"); } sr = answer.next(); count++; } break; } } catch (NamingException e) { // ignore if (log.isDebugEnabled()) { log.debug(e); } } } if (debug) { log.debug("Found role: " + sr.getNameInNamespace()); } // read the member attribute and get DNs of the users Attributes attributes = sr.getAttributes(); if (attributes != null) { NamingEnumeration attributeEntry = null; for (attributeEntry = attributes.getAll(); attributeEntry.hasMore();) { Attribute valAttribute = (Attribute) attributeEntry.next(); if (membershipProperty.equals(valAttribute.getID())) { NamingEnumeration values = null; for (values = valAttribute.getAll(); values.hasMore();) { String value = values.next().toString(); if (userDNList.size() >= maxItemLimit) { break; } userDNList.add(value); if (debug) { log.debug("Found attribute: " + membershipProperty + " value: " + value); } } } } } if (MEMBER_UID.equals(userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE))) { /* when the GroupEntryObjectClass is posixGroup, membership attribute is memberUid. We have to retrieve the DN using the memberUid. This procedure has to make an extra call to ldap. alternatively this can be done with a single ldap search using the memberUid and retrieving the display name and username. */ List<String> userDNListNew = new ArrayList<>(); for (String user : userDNList) { String userDN = getNameInSpaceForUserName(user); userDNListNew.add(userDN); } userDNList = userDNListNew; } // iterate over users' DN list and get userName and display name // attribute values String userNameProperty = userStoreProperties.get(LDAPConstants.USER_NAME_ATTRIBUTE); String displayNameAttribute = userStoreProperties.get(LDAPConstants.DISPLAY_NAME_ATTRIBUTE); String[] returnedAttributes = { userNameProperty, displayNameAttribute }; for (String user : userDNList) { if (debug) { log.debug("Getting name attributes of: " + user); } Attributes userAttributes; try { // '\' and '"' characters need another level of escaping before searching userAttributes = dirContext.getAttributes(escapeDNForSearch(user), returnedAttributes); String displayName = null; String userName = null; if (userAttributes != null) { Attribute userNameAttribute = userAttributes.get(userNameProperty); if (userNameAttribute != null) { userName = (String) userNameAttribute.get(); if (debug) { log.debug("UserName: " + userName); } } if (org.apache.commons.lang.StringUtils.isNotEmpty(displayNameAttribute)) { Attribute displayAttribute = userAttributes.get(displayNameAttribute); if (displayAttribute != null) { displayName = (String) displayAttribute.get(); } if (debug) { log.debug("DisplayName: " + displayName); } } } // Username will be null in the special case where the // username attribute has changed to another // and having different userNameProperty than the current // user-mgt.xml if (userName != null) { user = UserStoreUtils.getCombinedName(userName, displayName); userList.add(user); if (debug) { log.debug(user + " is added to the result list"); } } else { if (log.isDebugEnabled()) { log.debug( "User " + user + " doesn't have the user name property : " + userNameProperty); } } } catch (NamingException e) { if (log.isDebugEnabled()) { log.debug("Error in reading user information in the user store for the user " + user + e.getMessage(), e); } } } names = userList.toArray(new String[userList.size()]); } catch (PartialResultException e) { // can be due to referrals in AD. so just ignore error String errorMessage = "Error in reading user information in the user store"; if (isIgnorePartialResultException()) { if (log.isDebugEnabled()) { log.debug(errorMessage, e); } } else { throw new UserStoreException(errorMessage, e); } } catch (NamingException e) { String errorMessage = "Error in reading user information in the user store"; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } return names; }
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 v a 2 s .c om*/ // 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.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
/** * *//* www. j a v a 2 s.co m*/ public String[] getUserListOfLDAPRole(RoleContext context, String filter) throws UserStoreException { boolean debug = log.isDebugEnabled(); if (debug) { log.debug("Getting user list of role: " + context.getRoleName() + " with filter: " + filter); } List<String> userList = new ArrayList<String>(); String[] names = new String[0]; int givenMax = UserCoreConstants.MAX_USER_ROLE_LIST; int searchTime = UserCoreConstants.MAX_SEARCH_TIME; try { givenMax = Integer.parseInt( realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST)); } catch (Exception e) { givenMax = UserCoreConstants.MAX_USER_ROLE_LIST; } try { searchTime = Integer.parseInt( realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_SEARCH_TIME)); } catch (Exception e) { searchTime = UserCoreConstants.MAX_SEARCH_TIME; } DirContext dirContext = null; NamingEnumeration<SearchResult> answer = null; try { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setTimeLimit(searchTime); searchCtls.setCountLimit(givenMax); String searchFilter = ((LDAPRoleContext) context).getListFilter(); String roleNameProperty = ((LDAPRoleContext) context).getRoleNameProperty(); searchFilter = "(&" + searchFilter + "(" + roleNameProperty + "=" + escapeSpecialCharactersForFilter(context.getRoleName()) + "))"; String membershipProperty = realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE); String returnedAtts[] = { membershipProperty }; searchCtls.setReturningAttributes(returnedAtts); List<String> userDNList = new ArrayList<String>(); SearchResult sr = null; dirContext = connectionSource.getContext(); // with DN patterns if (((LDAPRoleContext) context).getRoleDNPatterns().size() > 0) { for (String pattern : ((LDAPRoleContext) context).getRoleDNPatterns()) { if (debug) { log.debug("Using pattern: " + pattern); } pattern = MessageFormat.format(pattern.trim(), escapeSpecialCharactersForDN(context.getRoleName())); try { answer = dirContext.search(escapeDNForSearch(pattern), searchFilter, searchCtls); if (answer.hasMore()) { sr = (SearchResult) answer.next(); break; } } catch (NamingException e) { // ignore if (log.isDebugEnabled()) { log.debug(e); } } } } if (sr == null) { // handling multiple search bases String searchBases = ((LDAPRoleContext) context).getSearchBase(); String[] roleSearchBaseArray = searchBases.split("#"); for (String searchBase : roleSearchBaseArray) { if (debug) { log.debug("Searching role: " + context.getRoleName() + " SearchBase: " + searchBase + " SearchFilter: " + searchFilter); } try { // read the DN of users who are members of the group answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls); int count = 0; if (answer.hasMore()) { // to check if there is a result while (answer.hasMore()) { // to check if there are more than one group if (count > 0) { throw new UserStoreException("More than one group exist with name"); } sr = (SearchResult) answer.next(); count++; } break; } } catch (NamingException e) { // ignore if (log.isDebugEnabled()) { log.debug(e); } } } } if (debug) { log.debug("Found role: " + sr.getNameInNamespace()); } // read the member attribute and get DNs of the users Attributes attributes = sr.getAttributes(); if (attributes != null) { NamingEnumeration attributeEntry = null; for (attributeEntry = attributes.getAll(); attributeEntry.hasMore();) { Attribute valAttribute = (Attribute) attributeEntry.next(); if (membershipProperty == null || membershipProperty.equals(valAttribute.getID())) { NamingEnumeration values = null; for (values = valAttribute.getAll(); values.hasMore();) { String value = values.next().toString(); userDNList.add(value); if (debug) { log.debug("Found attribute: " + membershipProperty + " value: " + value); } } } } } if (MEMBER_UID.equals(realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE))) { /* when the GroupEntryObjectClass is posixGroup, membership attribute is memberUid. We have to retrieve the DN using the memberUid. This procedure has to make an extra call to ldap. alternatively this can be done with a single ldap search using the memberUid and retrieving the display name and username. */ List<String> userDNListNew = new ArrayList<>(); for (String user : userDNList) { String userDN = getNameInSpaceForUserName(user); userDNListNew.add(userDN); } userDNList = userDNListNew; } // iterate over users' DN list and get userName and display name // attribute values String userNameProperty = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE); String displayNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.DISPLAY_NAME_ATTRIBUTE); String[] returnedAttributes = { userNameProperty, displayNameAttribute }; for (String user : userDNList) { if (debug) { log.debug("Getting name attributes of: " + user); } Attributes userAttributes; try { // '\' and '"' characters need another level of escaping before searching userAttributes = dirContext.getAttributes( user.replace("\\\\", "\\\\\\").replace("\\\"", "\\\\\""), returnedAttributes); String displayName = null; String userName = null; if (userAttributes != null) { Attribute userNameAttribute = userAttributes.get(userNameProperty); if (userNameAttribute != null) { userName = (String) userNameAttribute.get(); if (debug) { log.debug("UserName: " + userName); } } if (displayNameAttribute != null) { Attribute displayAttribute = userAttributes.get(displayNameAttribute); if (displayAttribute != null) { displayName = (String) displayAttribute.get(); } if (debug) { log.debug("DisplayName: " + displayName); } } } String domainName = realmConfig .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME); // Username will be null in the special case where the // username attribute has changed to another // and having different userNameProperty than the current // user-mgt.xml if (userName != null) { user = UserCoreUtil.getCombinedName(domainName, userName, displayName); userList.add(user); if (debug) { log.debug(user + " is added to the result list"); } } // Skip listing users which are not applicable to current // user-mgt.xml else { if (log.isDebugEnabled()) { log.debug( "User " + user + " doesn't have the user name property : " + userNameProperty); } } } catch (NamingException e) { if (log.isDebugEnabled()) { log.debug("Error in reading user information in the user store for the user " + user + e.getMessage(), e); } } } names = userList.toArray(new String[userList.size()]); } catch (PartialResultException e) { // can be due to referrals in AD. so just ignore error String errorMessage = "Error in reading user information in the user store for filter : " + filter; if (isIgnorePartialResultException()) { if (log.isDebugEnabled()) { log.debug(errorMessage, e); } } else { throw new UserStoreException(errorMessage, e); } } catch (NamingException e) { String errorMessage = "Error in reading user information in the user store for filter : " + filter; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } return names; }
From source file:com.alfaariss.oa.authentication.password.jndi.JNDIProtocolResource.java
private boolean doBind(String sUserID, String sPassword) throws OAException, UserException { StringBuffer sbTemp = null;//from w w w . jav a 2s . co m DirContext oDirContext = null; String sQuery = null; String sRelUserDn = null; boolean bResult = false; NamingEnumeration enumSearchResults = null; Hashtable<String, String> htEnvironment = new Hashtable<String, String>(); htEnvironment.put(Context.PROVIDER_URL, _sJNDIUrl); htEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, _sDriver); htEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple"); if (_bSSL) { htEnvironment.put(Context.SECURITY_PROTOCOL, "ssl"); } if (_sPrincipalDn.length() <= 0) // If no principal dn is known, we do a simple binding { String sEscUserID = JNDIUtil.escapeDN(sUserID); _logger.debug("Escaped user: " + sEscUserID); sbTemp = new StringBuffer(_sUserDn); sbTemp.append('='); sbTemp.append(sEscUserID); sbTemp.append(", "); sbTemp.append(_sBaseDn); htEnvironment.put(Context.SECURITY_PRINCIPAL, sbTemp.toString()); htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword); try { oDirContext = new InitialDirContext(htEnvironment); bResult = true; } catch (AuthenticationException e) { // If supplied credentials are invalid or when authentication fails // while accessing the directory or naming service. _logger.debug("Could not authenticate user (invalid password): " + sUserID, e); } catch (CommunicationException eC) { // If communication with the directory or naming service fails. _logger.warn("A communication error has occured", eC); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } catch (NamingException eN) { // The initial dir context could not be created. _logger.warn("A naming error has occured", eN); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } finally { try { if (oDirContext != null) { oDirContext.close(); } } catch (Exception e) { _logger.warn("Could not close connection with '" + _sJNDIUrl + '\'', e); } } } else //search through the subtree { // 1 - Try to bind to LDAP using the security principal's DN and its password htEnvironment.put(Context.SECURITY_PRINCIPAL, _sPrincipalDn); htEnvironment.put(Context.SECURITY_CREDENTIALS, _sPrincipalPwd); try { oDirContext = new InitialDirContext(htEnvironment); } catch (AuthenticationException eA) { _logger.warn("Could not bind to LDAP server", eA); throw new OAException(SystemErrors.ERROR_RESOURCE_CONNECT); } catch (CommunicationException eC) { _logger.warn("A communication error has occured", eC); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } catch (NamingException eN) { _logger.warn("A naming error has occured", eN); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } // 2 - Search through the context for user's DN relative to the base DN sQuery = resolveSearchQuery(sUserID); SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); try { enumSearchResults = oDirContext.search(_sBaseDn, sQuery, oScope); } catch (NamingException eN) { _logger.warn("User id not found in password backend for user: " + sUserID, eN); throw new UserException(UserEvent.AUTHN_METHOD_NOT_SUPPORTED); } finally { try { oDirContext.close(); oDirContext = null; } catch (Exception e) { _logger.warn("Could not close connection with '" + _sJNDIUrl + "'", e); } } try { if (!enumSearchResults.hasMoreElements()) { StringBuffer sb = new StringBuffer("User '"); sb.append(sUserID); sb.append("' not found during LDAP search. The filter was: '"); sb.append(sQuery); sb.append("'"); _logger.warn(sb.toString()); throw new UserException(UserEvent.AUTHN_METHOD_NOT_SUPPORTED); } SearchResult searchResult = (SearchResult) enumSearchResults.next(); sRelUserDn = searchResult.getName(); if (sRelUserDn == null) { _logger.warn("no user dn was returned for '" + sUserID + "'."); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } } catch (NamingException eN) { _logger.warn("failed to fetch profile of user '" + sUserID + "'.", eN); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } // 3 - Bind user using supplied credentials sbTemp = new StringBuffer(sRelUserDn); sbTemp.append(","); sbTemp.append(_sBaseDn); htEnvironment.put(Context.SECURITY_PRINCIPAL, sbTemp.toString()); htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword); try { oDirContext = new InitialDirContext(htEnvironment); bResult = true; } catch (AuthenticationException e) { _logger.debug("Could not authenticate user (invalid password): " + sUserID, e); } catch (CommunicationException eC) { _logger.warn("A communication error has occured", eC); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } catch (NamingException eN) { _logger.warn("A naming error has occured", eN); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } finally { try { if (oDirContext != null) { oDirContext.close(); } } catch (Exception e) { _logger.warn("Could not close connection with '" + _sJNDIUrl + "'.", e); } } } return bResult; }
From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
/** * *//*from w ww .jav a2 s. c o m*/ public Map<String, String> getUserPropertyValues(String userName, String[] propertyNames, String profileName) throws UserStoreException { String userAttributeSeparator = ","; String userDN = null; LdapName ldn = (LdapName) userCache.get(userName); if (ldn == null) { // read list of patterns from user-mgt.xml String patterns = realmConfig.getUserStoreProperty(LDAPConstants.USER_DN_PATTERN); if (patterns != null && !patterns.isEmpty()) { if (log.isDebugEnabled()) { log.debug("Using User DN Patterns " + patterns); } if (patterns.contains("#")) { userDN = getNameInSpaceForUserName(userName); } else { userDN = MessageFormat.format(patterns, escapeSpecialCharactersForDN(userName)); } } } else { userDN = ldn.toString(); } Map<String, String> values = new HashMap<String, String>(); // if user name contains domain name, remove domain name String[] userNames = userName.split(CarbonConstants.DOMAIN_SEPARATOR); if (userNames.length > 1) { userName = userNames[1]; } DirContext dirContext = this.connectionSource.getContext(); String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); String searchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); NamingEnumeration<?> answer = null; NamingEnumeration<?> attrs = null; try { if (userDN != null) { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); if (propertyNames != null && propertyNames.length > 0) { searchCtls.setReturningAttributes(propertyNames); } 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); } if (propertyNames == null) { log.debug("No attributes requested"); } else { for (String attribute : propertyNames) { log.debug("Requesting attribute :" + attribute); } } } try { answer = dirContext.search(escapeDNForSearch(userDN), searchFilter, searchCtls); } catch (PartialResultException e) { // can be due to referrals in AD. so just ignore error String errorMessage = "Error occurred while searching directory context for user : " + userDN + " searchFilter : " + searchFilter; if (isIgnorePartialResultException()) { if (log.isDebugEnabled()) { log.debug(errorMessage, e); } } else { throw new UserStoreException(errorMessage, e); } } catch (NamingException e) { String errorMessage = "Error occurred while searching directory context for user : " + userDN + " searchFilter : " + searchFilter; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } } else { answer = this.searchForUser(searchFilter, propertyNames, dirContext); } while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); Attributes attributes = sr.getAttributes(); if (attributes != null) { for (String name : propertyNames) { if (name != null) { Attribute attribute = attributes.get(name); if (attribute != null) { StringBuffer attrBuffer = new StringBuffer(); for (attrs = attribute.getAll(); attrs.hasMore();) { Object attObject = attrs.next(); String attr = null; if (attObject instanceof String) { attr = (String) attObject; } else if (attObject instanceof byte[]) { //if the attribute type is binary base64 encoded string will be returned attr = new String(Base64.encodeBase64((byte[]) attObject)); } if (attr != null && attr.trim().length() > 0) { String attrSeparator = realmConfig .getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR); if (attrSeparator != null && !attrSeparator.trim().isEmpty()) { userAttributeSeparator = attrSeparator; } attrBuffer.append(attr + userAttributeSeparator); } String value = attrBuffer.toString(); /* * Length needs to be more than userAttributeSeparator.length() for a valid * attribute, since we * attach userAttributeSeparator */ if (value != null && value.trim().length() > userAttributeSeparator.length()) { value = value.substring(0, value.length() - userAttributeSeparator.length()); values.put(name, value); } } } } } } } } catch (NamingException e) { String errorMessage = "Error occurred while getting user property values for user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { // close the naming enumeration and free up resources JNDIUtil.closeNamingEnumeration(attrs); JNDIUtil.closeNamingEnumeration(answer); // close directory context JNDIUtil.closeContext(dirContext); } return values; }