Example usage for javax.naming.ldap LdapName toString

List of usage examples for javax.naming.ldap LdapName toString

Introduction

In this page you can find the example usage for javax.naming.ldap LdapName toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of this LDAP name in a format defined by <a href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a> and described in the class description.

Usage

From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java

/**
 * {@inheritDoc}//from ww  w  .j  a  v  a2s .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  w  w  .  ja  v  a  2 s . co m
 * @return
 * @throws UserStoreException
 */
protected String getNameInSpaceForUserName(String userName) throws UserStoreException {
    // check the cache first
    LdapName ldn = (LdapName) userCache.get(userName);
    if (ldn != null) {
        return ldn.toString();
    }

    String searchBase = null;
    String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName));
    String userDNPattern = realmConfig.getUserStoreProperty(LDAPConstants.USER_DN_PATTERN);
    if (userDNPattern != null && userDNPattern.trim().length() > 0) {
        String[] patterns = userDNPattern.split("#");
        for (String pattern : patterns) {
            searchBase = MessageFormat.format(pattern, escapeSpecialCharactersForDN(userName));
            String userDN = getNameInSpaceForUserName(userName, searchBase, userSearchFilter);
            // check in another DN pattern
            if (userDN != null) {
                return userDN;
            }
        }
    }

    searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);

    return getNameInSpaceForUserName(userName, searchBase, userSearchFilter);

}

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 ww w. j  a  v a 2 s . c  o  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;
}

From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java

/**
 * This method escapes the special characters in a LdapName
 * according to the ldap filter escaping standards
 * @param ldn//  w  w  w .  j a  va  2s  .  c  o m
 * @return
 */
private String escapeLdapNameForFilter(LdapName ldn) {

    if (ldn == null) {
        if (log.isDebugEnabled()) {
            log.debug("Received null value to escape special characters. Returning null");
        }
        return null;
    }

    boolean replaceEscapeCharacters = true;

    String replaceEscapeCharactersAtUserLoginString = realmConfig.getUserStoreProperty(
            UserCoreConstants.RealmConfig.PROPERTY_REPLACE_ESCAPE_CHARACTERS_AT_USER_LOGIN);

    if (replaceEscapeCharactersAtUserLoginString != null) {
        replaceEscapeCharacters = Boolean.parseBoolean(replaceEscapeCharactersAtUserLoginString);
        if (log.isDebugEnabled()) {
            log.debug("Replace escape characters configured to: " + replaceEscapeCharactersAtUserLoginString);
        }
    }

    if (replaceEscapeCharacters) {
        String escapedDN = "";
        for (int i = ldn.size() - 1; i > -1; i--) { //escaping the rdns separately and re-constructing the DN
            escapedDN = escapedDN + escapeSpecialCharactersForFilterWithStarAsRegex(ldn.get(i));
            if (i != 0) {
                escapedDN += ",";
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Escaped DN value for filter : " + escapedDN);
        }
        return escapedDN;
    } else {
        return ldn.toString();
    }
}