Example usage for javax.naming.ldap LdapName getRdns

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

Introduction

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

Prototype

public List<Rdn> getRdns() 

Source Link

Document

Retrieves the list of relative distinguished names.

Usage

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java

public CertificateResponse verifyCertificateDN(String distinguishedName) throws KeystoreException {
    CertificateResponse lookUpCertificate = null;
    KeyStoreReader keyStoreReader = new KeyStoreReader();
    if (distinguishedName != null && !distinguishedName.isEmpty()) {
        if (distinguishedName.contains("/CN=")) {
            String[] dnSplits = distinguishedName.split("/CN=");
            String commonNameExtracted = dnSplits[dnSplits.length - 1];
            lookUpCertificate = keyStoreReader.getCertificateBySerial(commonNameExtracted);
        } else {/*  www.  j a  v a2s.  c o  m*/
            LdapName ldapName;
            try {
                ldapName = new LdapName(distinguishedName);
            } catch (InvalidNameException e) {
                throw new KeystoreException(
                        "Invalid name exception while trying to create a LDAP name using the distinguished name ",
                        e);
            }
            for (Rdn relativeDistinguishedNames : ldapName.getRdns()) {
                if (relativeDistinguishedNames.getType().equalsIgnoreCase("CN")) {
                    lookUpCertificate = keyStoreReader
                            .getCertificateBySerial(String.valueOf(relativeDistinguishedNames.getValue()));
                    break;
                }
            }
        }
    }
    return lookUpCertificate;
}

From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java

/**
 * @param userName Username of the user.
 * @param searchBase Search base group search base.
 * @return List of roles of the given user.
 * @throws UserStoreException If an error occurs while retrieving data from LDAP userstore.
 *///from   www .  j  a  v  a  2  s. c  o m
private String[] getLDAPRoleListOfUser(String userName, String searchBase) throws UserStoreException {
    boolean debug = log.isDebugEnabled();
    List<String> list;

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    // Load normal roles with the user
    String searchFilter;
    String roleNameProperty;
    searchFilter = userStoreProperties.get(LDAPConstants.GROUP_NAME_LIST_FILTER);
    roleNameProperty = userStoreProperties.get(LDAPConstants.GROUP_NAME_ATTRIBUTE);

    String membershipProperty = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
    String userDNPattern = userStoreProperties.get(LDAPConstants.USER_DN_PATTERN);
    String nameInSpace;
    if (userDNPattern != null && userDNPattern.trim().length() > 0
            && !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);
            if (MEMBER_UID.equals(userStoreProperties.get(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) {
            log.error("Error while creating LDAP name from: " + nameInSpace);
            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);

    String[] result = list.toArray(new String[list.size()]);

    for (String rolename : result) {
        log.debug("Found role: " + rolename);
    }
    return result;
}

From source file:org.wso2.carbon.identity.agent.userstore.manager.ldap.LDAPUserStoreManager.java

/**
 * @param userName Username of the user.
 * @param searchBase Search base group search base.
 * @return List of roles of the given user.
 * @throws UserStoreException If an error occurs while retrieving data from LDAP userstore.
 *///from   ww  w  .  jav  a  2 s.  c o m
private String[] getLDAPRoleListOfUser(String userName, String searchBase) throws UserStoreException {
    boolean debug = log.isDebugEnabled();
    List<String> list;

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    // Load normal roles with the user
    String searchFilter;
    String roleNameProperty;
    searchFilter = userStoreProperties.get(LDAPConstants.GROUP_NAME_LIST_FILTER);
    roleNameProperty = userStoreProperties.get(LDAPConstants.GROUP_NAME_ATTRIBUTE);

    String membershipProperty = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
    String userDNPattern = userStoreProperties.get(LDAPConstants.USER_DN_PATTERN);
    String nameInSpace;
    if (userDNPattern != null && userDNPattern.trim().length() > 0
            && !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);
            if (MEMBER_UID.equals(userStoreProperties.get(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) {
            log.error("Error while creating LDAP name from: " + nameInSpace);
            throw new UserStoreException(
                    "Invalid naming org.wso2.carbon.identity.agent.outbound.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);

    String[] result = list.toArray(new String[list.size()]);

    for (String rolename : result) {
        log.debug("Found role: " + rolename);
    }
    return result;
}

From source file:org.wso2.carbon.identity.authenticator.x509Certificate.X509CertificateAuthenticator.java

/**
 * get String that matches UsernameRegex from subjectDN.
 *
 * @param certAttributes        certificate x500 principal
 * @param authenticationContext authentication context
 * @throws AuthenticationFailedException
 *//*from w ww  .  j a va2s .  c om*/
private String getMatchedSubjectAttribute(String certAttributes, AuthenticationContext authenticationContext)
        throws AuthenticationFailedException {

    LdapName ldapDN;
    try {
        ldapDN = new LdapName(certAttributes);
    } catch (InvalidNameException e) {
        throw new AuthenticationFailedException("error occurred while get the certificate claims", e);
    }
    String userNameAttribute = getAuthenticatorConfig().getParameterMap()
            .get(X509CertificateConstants.USERNAME);
    List<String> matchedStringList = new ArrayList<>();
    for (Rdn distinguishNames : ldapDN.getRdns()) {
        if (subjectPatternCompiled != null && userNameAttribute.equals(distinguishNames.getType())) {
            Matcher m = subjectPatternCompiled.matcher(String.valueOf(distinguishNames.getValue()));
            addMatchStringsToList(m, matchedStringList);
        }
    }
    if (matchedStringList.isEmpty()) {
        authenticationContext.setProperty(X509CertificateConstants.X509_CERTIFICATE_ERROR_CODE,
                X509CertificateConstants.X509_CERTIFICATE_SUBJECTDN_REGEX_NO_MATCHES_ERROR_CODE);
        log.debug(X509CertificateConstants.X509_CERTIFICATE_SUBJECTDN_REGEX_NO_MATCHES_ERROR);
        throw new AuthenticationFailedException(
                X509CertificateConstants.X509_CERTIFICATE_SUBJECTDN_REGEX_NO_MATCHES_ERROR);
    } else if (matchedStringList.size() > 1) {
        authenticationContext.setProperty(X509CertificateConstants.X509_CERTIFICATE_ERROR_CODE,
                X509CertificateConstants.X509_CERTIFICATE_SUBJECTDN_REGEX_MULTIPLE_MATCHES_ERROR_CODE);
        log.debug("More than one value matched with the given regex, matches: "
                + Arrays.toString(matchedStringList.toArray()));
        throw new AuthenticationFailedException("More than one value matched with the given regex");
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Setting X509Certificate username attribute: " + userNameAttribute + " ,and value is "
                    + matchedStringList.get(0));
        }
        authenticationContext.setProperty(X509CertificateConstants.X509_CERTIFICATE_USERNAME,
                matchedStringList.get(0));
        return matchedStringList.get(0);
    }
}

From source file:org.wso2.carbon.identity.authenticator.x509Certificate.X509CertificateAuthenticator.java

/**
 * @param authenticationContext authentication context
 * @param certAttributes        principal attributes from certificate.
 * @return claim map// ww w .  ja va 2s . com
 * @throws AuthenticationFailedException
 */
protected Map<ClaimMapping, String> getSubjectAttributes(AuthenticationContext authenticationContext,
        String certAttributes) throws AuthenticationFailedException {
    Map<ClaimMapping, String> claims = new HashMap<>();
    LdapName ldapDN;
    try {
        ldapDN = new LdapName(certAttributes);
    } catch (InvalidNameException e) {
        throw new AuthenticationFailedException("error occurred while get the certificate claims", e);
    }
    String userNameAttribute = getAuthenticatorConfig().getParameterMap()
            .get(X509CertificateConstants.USERNAME);
    if (log.isDebugEnabled()) {
        log.debug("Getting username attribute: " + userNameAttribute);
    }
    for (Rdn distinguishNames : ldapDN.getRdns()) {
        claims.put(ClaimMapping.build(distinguishNames.getType(), distinguishNames.getType(), null, false),
                String.valueOf(distinguishNames.getValue()));
        if (StringUtils.isNotEmpty(userNameAttribute)) {
            if (userNameAttribute.equals(distinguishNames.getType())) {
                if (log.isDebugEnabled()) {
                    log.debug("Setting X509Certificate username attribute: " + userNameAttribute
                            + "and value is " + distinguishNames.getValue());
                }
                authenticationContext.setProperty(X509CertificateConstants.X509_CERTIFICATE_USERNAME,
                        String.valueOf(distinguishNames.getValue()));
            }
        }
    }
    return claims;
}

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

/**
 * {@inheritDoc}//from  w  ww  . ja  v a 2s . co 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

private boolean isInSearchBase(LdapName dn, LdapName searchBase) {

    List<Rdn> baseRdns = searchBase.getRdns();
    return dn.endsWith(baseRdns);
}

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

/**
 * @param groupDNs//ww  w .  java  2  s  .co m
 * @return
 * @throws UserStoreException
 */
private List<String> getGroupNameAttributeValuesOfGroups(List<LdapName> groupDNs) throws UserStoreException {
    log.debug("GetGroupNameAttributeValuesOfGroups with DN");
    boolean debug = log.isDebugEnabled();
    // get the DNs of the groups to which user belongs to, as per the search
    // parameters
    String groupNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.GROUP_NAME_ATTRIBUTE);
    String[] returnedAttributes = { groupNameAttribute };
    List<String> groupNameAttributeValues = new ArrayList<String>();
    DirContext dirContext = null;
    try {
        dirContext = this.connectionSource.getContext();

        for (LdapName group : groupDNs) {
            if (!isInSearchBase(group, new LdapName(groupSearchBase))) {
                // ignore those groups outside the group search base
                continue;
            }
            if (debug) {
                log.debug("Using DN: " + group);
            }

            Rdn rdn = group.getRdn(group.getRdns().size() - 1);
            // get the last element of the RDNs.

            if (rdn.getType().equalsIgnoreCase(groupNameAttribute)) {
                /*
                * Checking to see if the required information can be retrieved from the RDN
                * If so, we can add that value and continue without creating an LDAP context
                * Connection
                * */
                groupNameAttributeValues.add(rdn.getValue().toString());
                continue;
            }

            Attributes groupAttributes = dirContext.getAttributes(group, returnedAttributes);
            if (groupAttributes != null) {
                Attribute groupAttribute = groupAttributes.get(groupNameAttribute);
                if (groupAttribute != null) {
                    String groupNameAttributeValue = (String) groupAttribute.get();
                    if (debug) {
                        log.debug(groupNameAttribute + " : " + groupNameAttributeValue);
                    }
                    groupNameAttributeValues.add(groupNameAttributeValue);
                }
            }
        }
    } catch (UserStoreException e) {
        String errorMessage = "Error in getting group name attribute values of groups";
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } catch (NamingException e) {
        String errorMessage = "Error in getting group name attribute values of groups";
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeContext(dirContext);
    }
    return groupNameAttributeValues;
}