List of usage examples for javax.naming.directory SearchControls setSearchScope
public void setSearchScope(int scope)
From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java
public ServerPrinciple[] listServicePrinciples(String filter) throws DirectoryServerManagerException { ServerPrinciple[] serverNames = null; int maxItemLimit = Integer.parseInt( this.realmConfiguration.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST)); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setCountLimit(maxItemLimit); if (filter.contains("?") || filter.contains("**")) { log.error("Invalid search character " + filter); throw new DirectoryServerManagerException( "Invalid character sequence entered for service principle search. Please enter valid sequence."); }//from w ww . java2 s . c o m StringBuilder searchFilter; searchFilter = new StringBuilder( this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER)); String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); StringBuilder buff = new StringBuilder(); buff.append("(&").append(searchFilter).append("(") .append(LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE).append("=").append(filter) .append(")").append(getServerPrincipleIncludeString()).append(")"); String[] returnedAtts = { LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE, LDAPServerManagerConstants.LDAP_COMMON_NAME }; searchCtls.setReturningAttributes(returnedAtts); DirContext dirContext = null; try { dirContext = connectionSource.getContext(); NamingEnumeration<SearchResult> answer = dirContext.search(searchBase, buff.toString(), searchCtls); List<ServerPrinciple> list = new ArrayList<ServerPrinciple>(); int i = 0; while (answer.hasMoreElements() && i < maxItemLimit) { SearchResult sr = answer.next(); if (sr.getAttributes() != null) { Attribute serverNameAttribute = sr.getAttributes() .get(LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE); Attribute serverDescription = sr.getAttributes() .get(LDAPServerManagerConstants.LDAP_COMMON_NAME); if (serverNameAttribute != null) { ServerPrinciple principle; String serviceName; String serverPrincipleFullName = (String) serverNameAttribute.get(); if (serverPrincipleFullName.toLowerCase(Locale.ENGLISH) .contains(LDAPServerManagerConstants.KERBEROS_TGT)) { continue; } if (serverPrincipleFullName.contains("@")) { serviceName = serverPrincipleFullName.split("@")[0]; } else { serviceName = serverPrincipleFullName; } if (serverDescription != null) { principle = new ServerPrinciple(serviceName, (String) serverDescription.get()); } else { principle = new ServerPrinciple(serviceName); } list.add(principle); i++; } } } serverNames = list.toArray(new ServerPrinciple[list.size()]); Arrays.sort(serverNames); } catch (NamingException e) { log.error(e.getMessage(), e); throw new DirectoryServerManagerException("Unable to list service principles.", e); } catch (UserStoreException e) { log.error("Unable to retrieve LDAP connection context.", e); throw new DirectoryServerManagerException("Unable to list service principles.", e); } finally { try { JNDIUtil.closeContext(dirContext); } catch (UserStoreException e) { log.error("Unable to close directory context.", e); } } return serverNames; }
From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java
public void updateServicePrinciplePassword(String serverName, Object oldCredential, Object newCredentials) throws DirectoryServerManagerException { DirContext dirContext;//from ww w.jav a2s . c o m try { dirContext = this.connectionSource.getContext(); } catch (UserStoreException e) { throw new DirectoryServerManagerException("Unable to retrieve directory connection.", e); } //first search the existing user entry. String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String searchFilter = getServicePrincipleFilter(serverName); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(new String[] { LDAPServerManagerConstants.LDAP_PASSWORD }); try { NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, searchFilter, searchControls); // here we assume only one user while (namingEnumeration.hasMore()) { BasicAttributes basicAttributes = new BasicAttributes(true); SearchResult searchResult = namingEnumeration.next(); Attributes attributes = searchResult.getAttributes(); Attribute userPassword = attributes.get(LDAPServerManagerConstants.LDAP_PASSWORD); Attribute newPasswordAttribute = getChangePasswordAttribute(userPassword, oldCredential, newCredentials); basicAttributes.put(newPasswordAttribute); String dnName = searchResult.getName(); dirContext = (DirContext) dirContext.lookup(searchBase); dirContext.modifyAttributes(dnName, DirContext.REPLACE_ATTRIBUTE, basicAttributes); } } catch (NamingException e) { log.error("Unable to update server principle password details. Server name - " + serverName); throw new DirectoryServerManagerException("Can not access the directory service", e); } finally { try { JNDIUtil.closeContext(dirContext); } catch (UserStoreException e) { log.error("Unable to close directory context.", e); } } }
From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java
public boolean isValidPassword(String serverName, Object existingCredentials) throws DirectoryServerManagerException { DirContext dirContext;/*from w ww . j a v a2s.co m*/ try { dirContext = this.connectionSource.getContext(); } catch (UserStoreException e) { throw new DirectoryServerManagerException("Unable to retrieve directory connection.", e); } //first search the existing user entry. String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String searchFilter = getServicePrincipleFilter(serverName); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(new String[] { LDAPServerManagerConstants.LDAP_PASSWORD }); try { NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, searchFilter, searchControls); // here we assume only one user while (namingEnumeration.hasMore()) { SearchResult searchResult = namingEnumeration.next(); Attributes attributes = searchResult.getAttributes(); Attribute userPassword = attributes.get(LDAPServerManagerConstants.LDAP_PASSWORD); NamingEnumeration passwords = userPassword.getAll(); String passwordHashMethod = null; if (passwords.hasMore()) { byte[] byteArray = (byte[]) passwords.next(); String password = new String(byteArray, StandardCharsets.UTF_8); if (password.startsWith("{")) { passwordHashMethod = password.substring(password.indexOf("{") + 1, password.indexOf("}")); } return password.equals(getPasswordToStore((String) existingCredentials, passwordHashMethod)); } } } catch (NamingException e) { log.error("Failed, validating password. Can not access the directory service", e); throw new DirectoryServerManagerException( "Failed, validating password. " + "Can not access the directory service", e); } finally { try { JNDIUtil.closeContext(dirContext); } catch (UserStoreException e) { log.error("Unable to close directory context.", e); } } return false; }
From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java
private String lookupUserId(String serverName) throws DirectoryServerManagerException { DirContext dirContext;//from w ww .jav a2 s . co m try { dirContext = this.connectionSource.getContext(); } catch (UserStoreException e) { throw new DirectoryServerManagerException("Unable to retrieve directory connection.", e); } String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); //first search the existing user entry. String searchFilter = getServicePrincipleFilter(serverName); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(new String[] { "uid" }); try { NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, searchFilter, searchControls); // here we assume only one user if (namingEnumeration.hasMore()) { SearchResult searchResult; searchResult = namingEnumeration.next(); Attributes attributes = searchResult.getAttributes(); Attribute userId = attributes.get("uid"); return (String) userId.get(); } else { return null; } } catch (NamingException e) { log.error("Could not find user id for given server " + serverName, e); throw new DirectoryServerManagerException("Could not find user id for given server " + serverName, e); } finally { try { JNDIUtil.closeContext(dirContext); } catch (UserStoreException e) { log.error("Unable to close directory context.", e); } } }
From source file:org.wso2.carbon.identity.account.suspension.notification.task.ldap.LDAPNotificationReceiversRetrieval.java
@Override public List<NotificationReceiver> getNotificationReceivers(long lookupMin, long lookupMax, long delayForSuspension, String tenantDomain) throws AccountSuspensionNotificationException { List<NotificationReceiver> users = new ArrayList<NotificationReceiver>(); if (realmConfiguration != null) { String ldapSearchBase = realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); RealmService realmService = NotificationTaskDataHolder.getInstance().getRealmService(); try {//from w w w. java 2 s . com ClaimManager claimManager = (ClaimManager) realmService .getTenantUserRealm(IdentityTenantUtil.getTenantId(tenantDomain)).getClaimManager(); String userStoreDomain = realmConfiguration .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME); if (StringUtils.isBlank(userStoreDomain)) { userStoreDomain = IdentityUtil.getPrimaryDomainName(); } String usernameMapAttribute = claimManager.getAttributeName(userStoreDomain, NotificationConstants.USERNAME_CLAIM); String firstNameMapAttribute = claimManager.getAttributeName(userStoreDomain, NotificationConstants.FIRST_NAME_CLAIM); String emailMapAttribute = claimManager.getAttributeName(userStoreDomain, NotificationConstants.EMAIL_CLAIM); String lastLoginTimeAttribute = claimManager.getAttributeName(userStoreDomain, NotificationConstants.LAST_LOGIN_TIME); if (log.isDebugEnabled()) { log.debug( "Retrieving ldap user list for lookupMin: " + lookupMin + " - lookupMax: " + lookupMax); } LDAPConnectionContext ldapConnectionContext = new LDAPConnectionContext(realmConfiguration); DirContext ctx = ldapConnectionContext.getContext(); //carLicense is the mapped LDAP attribute for LastLoginTime claim String searchFilter = "(&(" + lastLoginTimeAttribute + ">=" + lookupMin + ")(" + lastLoginTimeAttribute + "<=" + lookupMax + "))"; SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> results = ctx.search(ldapSearchBase, searchFilter, searchControls); if (log.isDebugEnabled()) { log.debug("LDAP user list retrieved."); } while (results.hasMoreElements()) { SearchResult result = results.nextElement(); NotificationReceiver receiver = new NotificationReceiver(); receiver.setEmail((String) result.getAttributes().get(emailMapAttribute).get()); receiver.setUsername((String) result.getAttributes().get(usernameMapAttribute).get()); receiver.setFirstName((String) result.getAttributes().get(firstNameMapAttribute).get()); receiver.setUserStoreDomain(userStoreDomain); long lastLoginTime = Long .parseLong(result.getAttributes().get(lastLoginTimeAttribute).get().toString()); long expireDate = lastLoginTime + TimeUnit.DAYS.toMillis(delayForSuspension); receiver.setExpireDate(new SimpleDateFormat("dd-MM-yyyy").format(new Date(expireDate))); if (log.isDebugEnabled()) { log.debug("Expire date was set to: " + receiver.getExpireDate()); } users.add(receiver); } } catch (NamingException e) { throw new AccountSuspensionNotificationException("Failed to filter users from LDAP user store.", e); } catch (UserStoreException e) { throw new AccountSuspensionNotificationException("Failed to load LDAP connection context.", e); } catch (org.wso2.carbon.user.api.UserStoreException e) { throw new AccountSuspensionNotificationException( "Error occurred while getting tenant user realm for " + "tenant:" + tenantDomain, e); } } return users; }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * {@inheritDoc}// w ww. j a v a2 s.co m */ public Map<String, String> getUserPropertyValues(String userName, String[] propertyNames) throws UserStoreException { String userAttributeSeparator = ","; String userDN = null; // read list of patterns from user-mgt.xml String patterns = userStoreProperties.get(LDAPConstants.USER_DN_PATTERN); if (patterns != null && !patterns.isEmpty()) { if (log.isDebugEnabled()) { log.debug("Using User DN Patterns " + patterns); } if (patterns.contains(CommonConstants.XML_PATTERN_SEPERATOR)) { userDN = getNameInSpaceForUserName(userName); } else { userDN = MessageFormat.format(patterns, escapeSpecialCharactersForDN(userName)); } } Map<String, String> values = new HashMap<>(); DirContext dirContext = this.connectionSource.getContext(); String userSearchFilter = userStoreProperties.get(LDAPConstants.USER_NAME_SEARCH_FILTER); String searchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); NamingEnumeration<?> answer = null; NamingEnumeration<?> attrs = null; NamingEnumeration<?> allAttrs = null; try { if (userDN != null) { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); if (propertyNames[0].equals(CommonConstants.WILD_CARD_FILTER)) { propertyNames = null; } searchCtls.setReturningAttributes(propertyNames); 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); } assert answer != null; while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); Attributes attributes = sr.getAttributes(); if (attributes != null) { for (allAttrs = attributes.getAll(); allAttrs.hasMore();) { Attribute attribute = (Attribute) allAttrs.next(); if (attribute != null) { StringBuilder attrBuffer = new StringBuilder(); 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), "UTF-8"); } if (attr != null && attr.trim().length() > 0) { String attrSeparator = userStoreProperties.get(MULTI_ATTRIBUTE_SEPARATOR); if (attrSeparator != null && !attrSeparator.trim().isEmpty()) { userAttributeSeparator = attrSeparator; } attrBuffer.append(attr).append(userAttributeSeparator); } String value = attrBuffer.toString(); /* * Length needs to be more than userAttributeSeparator.length() for a valid * attribute, since we * attach userAttributeSeparator */ if (value.trim().length() > userAttributeSeparator.length()) { value = value.substring(0, value.length() - userAttributeSeparator.length()); values.put(attribute.getID(), 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); } catch (UnsupportedEncodingException e) { String errorMessage = "Error occurred while Base64 encoding 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 resource JNDIUtil.closeNamingEnumeration(attrs); JNDIUtil.closeNamingEnumeration(answer); // close directory context JNDIUtil.closeContext(dirContext); } return values; }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * {@inheritDoc}/*from w w w .j ava 2 s . co m*/ */ 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; int searchTime; try { givenMax = Integer.parseInt(userStoreProperties.get(CommonConstants.PROPERTY_MAX_USER_LIST)); } catch (Exception e) { givenMax = CommonConstants.MAX_USER_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; } 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 search. Please enter valid sequence."); } StringBuilder searchFilter = new StringBuilder( userStoreProperties.get(LDAPConstants.USER_NAME_LIST_FILTER)); String searchBases = userStoreProperties.get(LDAPConstants.USER_SEARCH_BASE); String userNameProperty = userStoreProperties.get(LDAPConstants.USER_NAME_ATTRIBUTE); String serviceNameAttribute = "sn"; StringBuilder finalFilter = new StringBuilder(); // read the display name attribute - if provided String displayNameAttribute = userStoreProperties.get(LDAPConstants.DISPLAY_NAME_ATTRIBUTE); String[] returnedAtts; if (StringUtils.isNotEmpty(displayNameAttribute)) { 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<>(); try { dirContext = connectionSource.getContext(); // handle multiple search bases String[] searchBaseArray = searchBases.split(CommonConstants.XML_PATTERN_SEPERATOR); for (String searchBase : searchBaseArray) { answer = dirContext.search(escapeDNForSearch(searchBase), finalFilter.toString(), searchCtls); while (answer.hasMoreElements()) { SearchResult sr = 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 (attr != null) { String name = (String) attr.get(); 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.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * {@inheritDoc}// w w w.j ava 2s . com */ @Override public boolean doCheckIsUserInRole(String userName, String roleName) throws UserStoreException { boolean debug = log.isDebugEnabled(); String searchBases = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // read the roles with this membership property String searchFilter = userStoreProperties.get(LDAPConstants.GROUP_NAME_LIST_FILTER); String membershipProperty = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE); if (membershipProperty == null || membershipProperty.length() < 1) { throw new UserStoreException("Please set membership attribute"); } String roleNameProperty = userStoreProperties.get(LDAPConstants.GROUP_NAME_ATTRIBUTE); String userDNPattern = userStoreProperties.get(LDAPConstants.USER_DN_PATTERN); String nameInSpace; if (org.apache.commons.lang.StringUtils.isNotEmpty(userDNPattern) && !userDNPattern.contains(CommonConstants.XML_PATTERN_SEPERATOR)) { 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) { log.error("Error while creating LDAP name from: " + nameInSpace); 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 (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(CommonConstants.XML_PATTERN_SEPERATOR); 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; }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * {@inheritDoc}// w ww. j av a 2 s . c o 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.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * {@inheritDoc}/* ww w.jav a 2 s. c o m*/ */ @Override public boolean doCheckExistingRole(String roleName) throws UserStoreException { boolean debug = log.isDebugEnabled(); boolean isExisting = false; if (debug) { log.debug("Searching for role: " + roleName); } String searchFilter = userStoreProperties.get(LDAPConstants.GROUP_NAME_LIST_FILTER); String roleNameProperty = userStoreProperties.get(LDAPConstants.GROUP_NAME_ATTRIBUTE); searchFilter = "(&" + searchFilter + "(" + roleNameProperty + "=" + escapeSpecialCharactersForFilter(roleName) + "))"; String searchBases = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE); 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(); String[] roleSearchBaseArray = searchBases.split(CommonConstants.XML_PATTERN_SEPERATOR); for (String searchBase : roleSearchBaseArray) { 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); } } } } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } if (debug) { log.debug("Is role: " + roleName + " exist: " + isExisting); } return isExisting; }