List of usage examples for javax.naming.directory SearchControls setSearchScope
public void setSearchScope(int scope)
From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java
@Override public void doSetUserClaimValue(String userName, String claimURI, String value, String profileName) throws UserStoreException { // get the LDAP Directory context DirContext dirContext = this.connectionSource.getContext(); DirContext subDirContext = null; // search the relevant user entry by user name String userSearchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(null); NamingEnumeration<SearchResult> returnedResultList = null; String returnedUserEntry = null; try {//from w ww .jav a2 s . c o m returnedResultList = dirContext.search(escapeDNForSearch(userSearchBase), userSearchFilter, searchControls); // assume only one user is returned from the search // TODO:what if more than one user is returned returnedUserEntry = returnedResultList.next().getName(); } catch (NamingException e) { String errorMessage = "Results could not be retrieved from the directory context for user : " + userName; if (logger.isDebugEnabled()) { logger.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(returnedResultList); } try { Attributes updatedAttributes = new BasicAttributes(true); // if there is no attribute for profile configuration in LDAP, skip // updating it. // get the claimMapping related to this claimURI String attributeName = getClaimAtrribute(claimURI, userName, null); if ("CN".equals(attributeName)) { subDirContext = (DirContext) dirContext.lookup(userSearchBase); subDirContext.rename(returnedUserEntry, "CN=" + value); return; } Attribute currentUpdatedAttribute = new BasicAttribute(attributeName); /* if updated attribute value is null, remove its values. */ if (EMPTY_ATTRIBUTE_STRING.equals(value)) { currentUpdatedAttribute.clear(); } else { String claimSeparator = realmConfig.getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR); if (claimSeparator != null && !claimSeparator.trim().isEmpty()) { userAttributeSeparator = claimSeparator; } if (value.contains(userAttributeSeparator)) { StringTokenizer st = new StringTokenizer(value, userAttributeSeparator); while (st.hasMoreElements()) { String newVal = st.nextElement().toString(); if (newVal != null && newVal.trim().length() > 0) { currentUpdatedAttribute.add(newVal.trim()); } } } else { currentUpdatedAttribute.add(value); } } updatedAttributes.put(currentUpdatedAttribute); // update the attributes in the relevant entry of the directory // store subDirContext = (DirContext) dirContext.lookup(userSearchBase); subDirContext.modifyAttributes(returnedUserEntry, DirContext.REPLACE_ATTRIBUTE, updatedAttributes); } catch (org.wso2.carbon.user.api.UserStoreException e) { String errorMessage = "Error in obtaining claim mapping for user : " + userName; if (logger.isDebugEnabled()) { logger.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } catch (NamingException e) { handleException(e, userName); } finally { JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(dirContext); } }
From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
/** * *///from w w w .j a v a 2 s. c om 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; }
From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
protected boolean isExistingLDAPRole(RoleContext context) throws UserStoreException { boolean debug = log.isDebugEnabled(); boolean isExisting = false; String roleName = context.getRoleName(); if (debug) {//from w ww.jav a 2 s .co m log.debug("Searching for role: " + roleName); } String searchFilter = ((LDAPRoleContext) context).getListFilter(); String roleNameProperty = ((LDAPRoleContext) context).getRoleNameProperty(); searchFilter = "(&" + searchFilter + "(" + roleNameProperty + "=" + escapeSpecialCharactersForFilter(roleName) + "))"; String searchBases = ((LDAPRoleContext) context).getSearchBase(); if (debug) { log.debug("Using search filter: " + searchFilter); } SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setReturningAttributes(new String[] { roleNameProperty }); NamingEnumeration<SearchResult> answer = null; DirContext dirContext = null; try { 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(roleName)); try { answer = dirContext.search(escapeDNForSearch(pattern), searchFilter, searchCtls); } catch (NamingException e) { if (log.isDebugEnabled()) { log.debug(e); } // ignore } if (answer != null && answer.hasMoreElements()) { return true; } } } //try out with handle multiple search bases String[] roleSearchBaseArray = searchBases.split("#"); for (String searchBase : roleSearchBaseArray) { // no DN Patterns found if (debug) { log.debug("Searching in " + searchBase); } try { answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls); if (answer.hasMoreElements()) { isExisting = true; break; } } catch (NamingException e) { if (log.isDebugEnabled()) { log.debug(e); } // ignore } } } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } if (debug) { log.debug("Is role: " + roleName + " exist: " + isExisting); } return isExisting; }
From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
/** * *//*from w ww . ja v a 2 s . c om*/ public String[] doListUsers(String filter, int maxItemLimit) throws UserStoreException { boolean debug = log.isDebugEnabled(); String[] userNames = new String[0]; if (maxItemLimit == 0) { return userNames; } 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; } if (maxItemLimit < 0 || maxItemLimit > givenMax) { maxItemLimit = givenMax; } SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setCountLimit(maxItemLimit); searchCtls.setTimeLimit(searchTime); if (filter.contains("?") || filter.contains("**")) { throw new UserStoreException( "Invalid character sequence entered for user serch. Please enter valid sequence."); } StringBuffer searchFilter = new StringBuffer( realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER)); String searchBases = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userNameProperty = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE); String serviceNameAttribute = "sn"; StringBuffer finalFilter = new StringBuffer(); // read the display name attribute - if provided String displayNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.DISPLAY_NAME_ATTRIBUTE); String[] returnedAtts = null; if (displayNameAttribute != null) { returnedAtts = new String[] { userNameProperty, serviceNameAttribute, displayNameAttribute }; finalFilter.append("(&").append(searchFilter).append("(").append(displayNameAttribute).append("=") .append(escapeSpecialCharactersForFilterWithStarAsRegex(filter)).append("))"); } else { returnedAtts = new String[] { userNameProperty, serviceNameAttribute }; finalFilter.append("(&").append(searchFilter).append("(").append(userNameProperty).append("=") .append(escapeSpecialCharactersForFilterWithStarAsRegex(filter)).append("))"); } if (debug) { log.debug( "Listing users. SearchBase: " + searchBases + " Constructed-Filter: " + finalFilter.toString()); log.debug("Search controls. Max Limit: " + maxItemLimit + " Max Time: " + searchTime); } searchCtls.setReturningAttributes(returnedAtts); DirContext dirContext = null; NamingEnumeration<SearchResult> answer = null; List<String> list = new ArrayList<String>(); try { dirContext = connectionSource.getContext(); // handle multiple search bases String[] searchBaseArray = searchBases.split("#"); for (String searchBase : searchBaseArray) { answer = dirContext.search(escapeDNForSearch(searchBase), finalFilter.toString(), searchCtls); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); if (sr.getAttributes() != null) { log.debug("Result found .."); Attribute attr = sr.getAttributes().get(userNameProperty); /* * If this is a service principle, just ignore and * iterate rest of the array. The entity is a service if * value of surname is Service */ Attribute attrSurname = sr.getAttributes().get(serviceNameAttribute); if (attrSurname != null) { if (debug) { log.debug(serviceNameAttribute + " : " + attrSurname); } String serviceName = (String) attrSurname.get(); if (serviceName != null && serviceName.equals(LDAPConstants.SERVER_PRINCIPAL_ATTRIBUTE_VALUE)) { continue; } } /* * if display name is provided, read that attribute */ Attribute displayName = null; if (displayNameAttribute != null) { displayName = sr.getAttributes().get(displayNameAttribute); if (debug) { log.debug(displayNameAttribute + " : " + displayName); } } if (attr != null) { String name = (String) attr.get(); String display = null; if (displayName != null) { display = (String) displayName.get(); } // append the domain if exist String domain = this.getRealmConfiguration() .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME); // get the name in the format of // domainName/userName|domainName/displayName name = UserCoreUtil.getCombinedName(domain, name, display); list.add(name); } } } } userNames = list.toArray(new String[list.size()]); Arrays.sort(userNames); if (debug) { for (String username : userNames) { log.debug("result: " + username); } } } catch (PartialResultException e) { // can be due to referrals in AD. so just ignore error String errorMessage = "Error occurred while getting user list for filter : " + filter + "max limit : " + maxItemLimit; if (isIgnorePartialResultException()) { if (log.isDebugEnabled()) { log.debug(errorMessage, e); } } else { throw new UserStoreException(errorMessage, e); } } catch (NamingException e) { String errorMessage = "Error occurred while getting user list for filter : " + filter + "max limit : " + maxItemLimit; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } return userNames; }
From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
/** * @param searchFilter//from www.jav a 2s. c om * @param returnedAtts * @param dirContext * @return * @throws UserStoreException */ protected NamingEnumeration<SearchResult> searchForUser(String searchFilter, String[] returnedAtts, DirContext dirContext) throws UserStoreException { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchBases = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); if (returnedAtts != null && returnedAtts.length > 0) { searchCtls.setReturningAttributes(returnedAtts); } 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 (returnedAtts == null) { log.debug("No attributes requested"); } else { for (String attribute : returnedAtts) { log.debug("Requesting attribute :" + attribute); } } } String[] searchBaseAraay = searchBases.split("#"); NamingEnumeration<SearchResult> answer = null; try { for (String searchBase : searchBaseAraay) { answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls); if (answer.hasMore()) { return answer; } } } catch (PartialResultException e) { // can be due to referrals in AD. so just ignore error String errorMessage = "Error occurred while search user for filter : " + searchFilter; if (isIgnorePartialResultException()) { if (log.isDebugEnabled()) { log.debug(errorMessage, e); } } else { throw new UserStoreException(errorMessage, e); } } catch (NamingException e) { String errorMessage = "Error occurred while search user for filter : " + searchFilter; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } return answer; }
From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
/** * Returns the list of role names for the given search base and other * parameters//from w w w . j a v a 2 s.c om * * @param searchTime * @param filter * @param maxItemLimit * @param searchFilter * @param roleNameProperty * @param searchBase * @param appendTenantDomain * @return * @throws UserStoreException */ protected List<String> getLDAPRoleNames(int searchTime, String filter, int maxItemLimit, String searchFilter, String roleNameProperty, String searchBase, boolean appendTenantDomain) throws UserStoreException { boolean debug = log.isDebugEnabled(); List<String> roles = new ArrayList<String>(); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setCountLimit(maxItemLimit); searchCtls.setTimeLimit(searchTime); String returnedAtts[] = { roleNameProperty }; searchCtls.setReturningAttributes(returnedAtts); // / search filter TODO StringBuffer finalFilter = new StringBuffer(); finalFilter.append("(&").append(searchFilter).append("(").append(roleNameProperty).append("=") .append(escapeSpecialCharactersForFilterWithStarAsRegex(filter)).append("))"); if (debug) { log.debug("Listing roles. SearchBase: " + searchBase + " ConstructedFilter: " + finalFilter.toString()); } DirContext dirContext = null; NamingEnumeration<SearchResult> answer = null; try { dirContext = connectionSource.getContext(); answer = dirContext.search(escapeDNForSearch(searchBase), finalFilter.toString(), searchCtls); // append the domain if exist 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(roleNameProperty); if (attr != null) { String name = (String) attr.get(); name = UserCoreUtil.addDomainToName(name, domain); if (appendTenantDomain) { String dn = sr.getNameInNamespace(); name = UserCoreUtil.addTenantDomainToEntry(name, getTenantDomainFromRoleDN(dn, name)); } roles.add(name); } } } } catch (PartialResultException e) { // can be due to referrals in AD. so just ignore error String errorMessage = "Error occurred while getting LDAP role names. SearchBase: " + searchBase + " ConstructedFilter: " + finalFilter.toString(); if (isIgnorePartialResultException()) { if (log.isDebugEnabled()) { log.debug(errorMessage, e); } } else { throw new UserStoreException(errorMessage, e); } } catch (NamingException e) { String errorMessage = "Error occurred while getting LDAP role names. SearchBase: " + searchBase + " ConstructedFilter: " + finalFilter.toString(); if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } if (debug) { Iterator<String> rolesIte = roles.iterator(); while (rolesIte.hasNext()) { log.debug("result: " + rolesIte.next()); } } return roles; }
From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
/** * *///from w ww . java2 s.c o 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:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
/** * {@inheritDoc}/*from w ww .j a va 2 s . c o m*/ */ protected String[] getLDAPRoleListOfUser(String userName, String filter, String searchBase, boolean shared) throws UserStoreException { boolean debug = log.isDebugEnabled(); List<String> list = new ArrayList<String>(); /* * do not search REGISTRY_ANONNYMOUS_USERNAME or * REGISTRY_SYSTEM_USERNAME in LDAP because it * causes warn logs printed from embedded-ldap. */ if (readGroupsEnabled && (!UserCoreUtil.isRegistryAnnonymousUser(userName)) && (!UserCoreUtil.isRegistrySystemUser(userName))) { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String memberOfProperty = realmConfig.getUserStoreProperty(LDAPConstants.MEMBEROF_ATTRIBUTE); if (memberOfProperty != null && memberOfProperty.length() > 0) { // TODO Handle active directory shared roles logics here String userNameProperty = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE); String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); String searchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); String binaryAttribute = realmConfig.getUserStoreProperty(LDAPConstants.LDAP_ATTRIBUTES_BINARY); String primaryGroupId = realmConfig.getUserStoreProperty(LDAPConstants.PRIMARY_GROUP_ID); String returnedAtts[] = { memberOfProperty }; if (binaryAttribute != null && primaryGroupId != null) { returnedAtts = new String[] { memberOfProperty, binaryAttribute, primaryGroupId }; } searchCtls.setReturningAttributes(returnedAtts); if (debug) { log.debug("Reading roles with the memberOfProperty Property: " + memberOfProperty); } if (binaryAttribute != null && primaryGroupId != null) { list = this.getAttributeListOfOneElementWithPrimarGroup(searchBase, searchFilter, searchCtls, binaryAttribute, primaryGroupId, userNameProperty, memberOfProperty); } else { // use cache LdapName ldn = (LdapName) userCache.get(userName); if (ldn != null) { searchBase = ldn.toString(); } else { // create DN directly but there is no way when multiple DNs are used. Need to improve letter String userDNPattern = realmConfig.getUserStoreProperty(LDAPConstants.USER_DN_PATTERN); if (userDNPattern != null & userDNPattern.trim().length() > 0 && !userDNPattern.contains("#")) { searchBase = MessageFormat.format(userDNPattern, escapeSpecialCharactersForDN(userName)); } } // get DNs of the groups to which this user belongs List<String> groupDNs = this.getListOfNames(searchBase, searchFilter, searchCtls, memberOfProperty, false); List<LdapName> groups = new ArrayList<>(); for (String groupDN : groupDNs) { try { groups.add(new LdapName(groupDN)); } catch (InvalidNameException e) { if (log.isDebugEnabled()) { log.debug("Naming error : ", e); } } } /* * to be compatible with AD as well, we need to do a search * over the groups and * find those groups' attribute value defined for group name * attribute and * return */ list = this.getGroupNameAttributeValuesOfGroups(groups); } } else { // Load normal roles with the user String searchFilter; String roleNameProperty; if (shared) { searchFilter = realmConfig.getUserStoreProperty(LDAPConstants.SHARED_GROUP_NAME_LIST_FILTER); roleNameProperty = realmConfig.getUserStoreProperty(LDAPConstants.SHARED_GROUP_NAME_ATTRIBUTE); } else { searchFilter = realmConfig.getUserStoreProperty(LDAPConstants.GROUP_NAME_LIST_FILTER); roleNameProperty = realmConfig.getUserStoreProperty(LDAPConstants.GROUP_NAME_ATTRIBUTE); } String membershipProperty = realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE); String userDNPattern = realmConfig.getUserStoreProperty(LDAPConstants.USER_DN_PATTERN); String nameInSpace; if (userDNPattern != null && userDNPattern.trim().length() > 0 && !userDNPattern.contains("#")) { nameInSpace = MessageFormat.format(userDNPattern, escapeSpecialCharactersForDN(userName)); } else { nameInSpace = this.getNameInSpaceForUserName(userName); } // read the roles with this membership property if (membershipProperty == null || membershipProperty.length() < 1) { throw new UserStoreException("Please set member of attribute or membership attribute"); } String membershipValue; if (nameInSpace != null) { try { LdapName ldn = new LdapName(nameInSpace); if (MEMBER_UID .equals(realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE))) { // membership value of posixGroup is not DN of the user List rdns = ldn.getRdns(); membershipValue = ((Rdn) rdns.get(rdns.size() - 1)).getValue().toString(); } else { membershipValue = escapeLdapNameForFilter(ldn); } } catch (InvalidNameException e) { throw new UserStoreException("Invalid naming exception for: " + nameInSpace, e); } } else { return new String[0]; } searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + "))"; String returnedAtts[] = { roleNameProperty }; searchCtls.setReturningAttributes(returnedAtts); if (debug) { log.debug("Reading roles with the membershipProperty Property: " + membershipProperty); } list = this.getListOfNames(searchBase, searchFilter, searchCtls, roleNameProperty, false); } } else if (UserCoreUtil.isRegistryAnnonymousUser(userName)) { // returning a REGISTRY_ANONNYMOUS_ROLE_NAME for // REGISTRY_ANONNYMOUS_USERNAME list.add(CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME); } String[] result = list.toArray(new String[list.size()]); if (result != null) { for (String rolename : result) { log.debug("Found role: " + rolename); } } return result; }
From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
/** * @param userName//from w ww .ja va 2 s . c om * @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
@Override public boolean doCheckIsUserInRole(String userName, String roleName) throws UserStoreException { boolean debug = log.isDebugEnabled(); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); LDAPRoleContext context = (LDAPRoleContext) createRoleContext(roleName); // Get the effective search base String searchBases = this.getEffectiveSearchBase(context.isShared()); String memberOfProperty = realmConfig.getUserStoreProperty(LDAPConstants.MEMBEROF_ATTRIBUTE); if (memberOfProperty != null && memberOfProperty.length() > 0) { List<String> list; String userNameProperty = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE); String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); String searchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); String binaryAttribute = realmConfig.getUserStoreProperty(LDAPConstants.LDAP_ATTRIBUTES_BINARY); String primaryGroupId = realmConfig.getUserStoreProperty(LDAPConstants.PRIMARY_GROUP_ID); String returnedAtts[] = { memberOfProperty }; if (binaryAttribute != null && primaryGroupId != null) { returnedAtts = new String[] { memberOfProperty, binaryAttribute, primaryGroupId }; }//from w ww .j a v a 2 s .co m searchCtls.setReturningAttributes(returnedAtts); if (debug) { log.debug("Do check whether the user: " + userName + " is in role: " + roleName); log.debug("Search filter: " + searchFilter); for (String retAttrib : returnedAtts) { log.debug("Requesting attribute: " + retAttrib); } } if (binaryAttribute != null && primaryGroupId != null) { list = this.getAttributeListOfOneElementWithPrimarGroup(searchBases, searchFilter, searchCtls, binaryAttribute, primaryGroupId, userNameProperty, memberOfProperty); } else { // use cache LdapName ldn = (LdapName) userCache.get(userName); if (ldn != null) { searchBases = ldn.toString(); } else { // create DN directly but there is no way when multiple DNs are used. Need to improve letter String userDNPattern = realmConfig.getUserStoreProperty(LDAPConstants.USER_DN_PATTERN); if (userDNPattern != null && userDNPattern.trim().length() > 0 && !userDNPattern.contains("#")) { searchBases = MessageFormat.format(userDNPattern, escapeSpecialCharactersForDN(userName)); } } list = this.getAttributeListOfOneElement(searchBases, searchFilter, searchCtls); } if (debug) { if (list != null) { boolean isUserInRole = false; for (String item : list) { log.debug("Result: " + item); if (item.equalsIgnoreCase(roleName)) { isUserInRole = true; } } log.debug("Is user: " + userName + " in role: " + roleName + " ? " + isUserInRole); } else { log.debug("No results found !"); } } // adding roles list in to the cache if (list != null) { addAllRolesToUserRolesCache(userName, list); for (String role : list) { if (role.equalsIgnoreCase(roleName)) { return true; } } } } else { // read the roles with this membership property String searchFilter = realmConfig.getUserStoreProperty(LDAPConstants.GROUP_NAME_LIST_FILTER); String membershipProperty = realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE); if (membershipProperty == null || membershipProperty.length() < 1) { throw new UserStoreException("Please set member of attribute or membership attribute"); } String roleNameProperty = realmConfig.getUserStoreProperty(LDAPConstants.GROUP_NAME_ATTRIBUTE); String userDNPattern = realmConfig.getUserStoreProperty(LDAPConstants.USER_DN_PATTERN); String nameInSpace; if (userDNPattern != null && userDNPattern.trim().length() > 0 && !userDNPattern.contains("#")) { nameInSpace = MessageFormat.format(userDNPattern, escapeSpecialCharactersForDN(userName)); } else { nameInSpace = this.getNameInSpaceForUserName(userName); } String membershipValue; if (nameInSpace != null) { try { LdapName ldn = new LdapName(nameInSpace); membershipValue = escapeLdapNameForFilter(ldn); } catch (InvalidNameException e) { throw new UserStoreException("Invalid naming exception for: " + nameInSpace, e); } } else { return false; } searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + "))"; String returnedAtts[] = { roleNameProperty }; searchCtls.setReturningAttributes(returnedAtts); if (debug) { log.debug("Do check whether the user : " + userName + " is in role: " + roleName); log.debug("Search filter : " + searchFilter); for (String retAttrib : returnedAtts) { log.debug("Requesting attribute: " + retAttrib); } } DirContext dirContext = null; NamingEnumeration<SearchResult> answer = null; try { dirContext = connectionSource.getContext(); if (context.getRoleDNPatterns().size() > 0) { for (String pattern : context.getRoleDNPatterns()) { if (debug) { log.debug("Using pattern: " + pattern); } searchBases = MessageFormat.format(pattern.trim(), escapeSpecialCharactersForDN(roleName)); try { answer = dirContext.search(escapeDNForSearch(searchBases), searchFilter, searchCtls); } catch (NamingException e) { if (log.isDebugEnabled()) { log.debug(e); } //ignore } if (answer != null && answer.hasMoreElements()) { if (debug) { log.debug("User: " + userName + " in role: " + roleName); } return true; } if (debug) { log.debug("User: " + userName + " NOT in role: " + roleName); } } } else { if (debug) { log.debug("Do check whether the user: " + userName + " is in role: " + roleName); log.debug("Search filter: " + searchFilter); for (String retAttrib : returnedAtts) { log.debug("Requesting attribute: " + retAttrib); } } searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + ") (" + roleNameProperty + "=" + escapeSpecialCharactersForFilter(roleName) + "))"; // handle multiple search bases String[] searchBaseArray = searchBases.split("#"); for (String searchBase : searchBaseArray) { answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls); if (answer.hasMoreElements()) { if (debug) { log.debug("User: " + userName + " in role: " + roleName); } return true; } if (debug) { log.debug("User: " + userName + " NOT in role: " + roleName); } } } } catch (NamingException e) { if (log.isDebugEnabled()) { log.debug(e.getMessage(), e); } } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } } return false; }