Example usage for javax.naming.ldap LdapName LdapName

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

Introduction

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

Prototype

public LdapName(List<Rdn> rdns) 

Source Link

Document

Constructs an LDAP name given its parsed RDN components.

Usage

From source file:org.springframework.ldap.support.LdapUtilsTest.java

@Test
public void testGetStringValueIndexed() throws InvalidNameException {
    LdapName ldapName = new LdapName(EXPECTED_DN_STRING);
    assertThat("I").isEqualTo(LdapUtils.getValue(ldapName, 1));
}

From source file:org.wso2.carbon.apimgt.gateway.handlers.security.authenticator.MutualSSLAuthenticator.java

/**
 * To set the authentication context in current message context.
 *
 * @param messageContext Relevant message context.
 * @param sslCertObject  SSL certificate object.
 * @throws APISecurityException API Security Exception.
 */// w w  w . ja  v a  2 s .  co  m
private void setAuthContext(MessageContext messageContext, Object sslCertObject) throws APISecurityException {

    X509Certificate[] certs = (X509Certificate[]) sslCertObject;
    X509Certificate x509Certificate = certs[0];
    String subjectDN = x509Certificate.getSubjectDN().getName();
    String uniqueIdentifier = String
            .valueOf(x509Certificate.getSerialNumber() + "_" + x509Certificate.getIssuerDN())
            .replaceAll(",", "#").replaceAll("\"", "'").trim();
    String tier = certificates.get(uniqueIdentifier);
    if (StringUtils.isEmpty(tier)) {
        if (log.isDebugEnabled()) {
            log.debug(
                    "The client certificate presented is available in gateway, however it was not added against "
                            + "the API " + getAPIIdentifier(messageContext));
        }
        throw new APISecurityException(APISecurityConstants.MUTUAL_SSL_VALIDATION_FAILURE,
                APISecurityConstants.MUTUAL_SSL_VALIDATION_FAILURE_MESSAGE);
    }
    AuthenticationContext authContext = new AuthenticationContext();
    authContext.setAuthenticated(true);
    authContext.setUsername(subjectDN);
    try {
        LdapName ldapDN = new LdapName(subjectDN);
        for (Rdn rdn : ldapDN.getRdns()) {
            if (APIConstants.CERTIFICATE_COMMON_NAME.equalsIgnoreCase(rdn.getType())) {
                authContext.setUsername((String) rdn.getValue());
            }
        }
    } catch (InvalidNameException e) {
        log.warn("Cannot get the CN name from certificate:" + e.getMessage() + ". Please make sure the "
                + "certificate to include a proper common name that follows naming convention.");
        authContext.setUsername(subjectDN);
    }
    authContext.setApiTier(apiLevelPolicy);
    APIIdentifier apiIdentifier = getAPIIdentifier(messageContext);
    authContext.setKeyType(APIConstants.API_KEY_TYPE_PRODUCTION);
    authContext.setStopOnQuotaReach(true);
    authContext.setApiKey(uniqueIdentifier + "_" + apiIdentifier.toString());
    authContext.setTier(tier);
    /* For the mutual SSL based authenticated request, the resource level throttling is not considered, hence
    assigning the unlimited tier for that. */
    VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
    verbInfoDTO.setThrottling(APIConstants.UNLIMITED_TIER);
    messageContext.setProperty(APIConstants.VERB_INFO_DTO, verbInfoDTO);
    if (log.isDebugEnabled()) {
        log.debug("Auth context for the API " + getAPIIdentifier(messageContext) + ": Username["
                + authContext.getUsername() + "APIKey[(" + authContext.getApiKey() + "] Tier["
                + authContext.getTier() + "]");
    }
    APISecurityUtils.setAuthenticationContext(messageContext, authContext, null);
}

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 {//from  ww  w  . ja  va2  s .  com
            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

/**
 * {@inheritDoc}//ww  w  .  j av  a  2  s .  co  m
 */
@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

/**
 * @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 .j  ava2s.  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

/**
 * {@inheritDoc}/*  ww w . ja v a2s.  c o  m*/
 */
@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 org.wso2.carbon.identity.agent.outbound.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.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 w  ww . j  av  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 va  2 s .  c  o  m
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/*from www .j ava 2 s  .  co  m*/
 * @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

/**
 *
 *//*from w w w  .jav a 2 s.  c  o  m*/
public boolean doAuthenticate(String userName, Object credential) throws UserStoreException {

    boolean debug = log.isDebugEnabled();

    String failedUserDN = null;

    if (userName == null || credential == null) {
        return false;
    }

    userName = userName.trim();

    String password = (String) credential;
    password = password.trim();

    if (userName.equals("") || password.equals("")) {
        return false;
    }

    if (debug) {
        log.debug("Authenticating user " + userName);
    }

    boolean bValue = false;
    // check cached user DN first.
    String name = null;
    LdapName ldn = (LdapName) userCache.get(userName);
    if (ldn != null) {
        name = ldn.toString();
        try {
            if (debug) {
                log.debug("Cache hit. Using DN " + name);
            }
            bValue = this.bindAsUser(userName, name, (String) credential);
        } catch (NamingException e) {
            // do nothing if bind fails since we check for other DN
            // patterns as well.
            if (log.isDebugEnabled()) {
                log.debug("Checking authentication with UserDN " + name + "failed " + e.getMessage(), e);
            }
        }

        if (bValue) {
            return bValue;
        }
        // we need not check binding for this name again, so store this and check
        failedUserDN = name;

    }
    // read DN patterns from user-mgt.xml
    String patterns = realmConfig.getUserStoreProperty(LDAPConstants.USER_DN_PATTERN);

    if (patterns != null && !patterns.isEmpty()) {

        if (debug) {
            log.debug("Using UserDNPatterns " + patterns);
        }

        // if the property is present, split it using # to see if there are
        // multiple patterns specified.
        String[] userDNPatternList = patterns.split("#");
        if (userDNPatternList.length > 0) {
            for (String userDNPattern : userDNPatternList) {
                name = MessageFormat.format(userDNPattern, escapeSpecialCharactersForDN(userName));
                // check if the same name is found and checked from cache
                if (failedUserDN != null && failedUserDN.equalsIgnoreCase(name)) {
                    continue;
                }

                if (debug) {
                    log.debug("Authenticating with " + name);
                }
                try {
                    if (name != null) {
                        bValue = this.bindAsUser(userName, name, (String) credential);
                        if (bValue) {
                            LdapName ldapName = new LdapName(name);
                            userCache.put(userName, ldapName);
                            break;
                        }
                    }
                } catch (NamingException e) {
                    // do nothing if bind fails since we check for other DN
                    // patterns as well.
                    if (log.isDebugEnabled()) {
                        log.debug("Checking authentication with UserDN " + userDNPattern + "failed "
                                + e.getMessage(), e);
                    }
                }
            }
        }
    } else {
        name = getNameInSpaceForUserName(userName);
        try {
            if (name != null) {
                if (debug) {
                    log.debug("Authenticating with " + name);
                }
                bValue = this.bindAsUser(userName, name, (String) credential);
                if (bValue) {
                    LdapName ldapName = new LdapName(name);
                    userCache.put(userName, ldapName);
                }
            }
        } catch (NamingException e) {
            String errorMessage = "Cannot bind user : " + userName;
            if (log.isDebugEnabled()) {
                log.debug(errorMessage, e);
            }
            throw new UserStoreException(errorMessage, e);
        }
    }

    return bValue;
}