Example usage for javax.naming.ldap InitialLdapContext getNameInNamespace

List of usage examples for javax.naming.ldap InitialLdapContext getNameInNamespace

Introduction

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

Prototype

public String getNameInNamespace() throws NamingException 

Source Link

Usage

From source file:com.dianping.cat.system.page.login.service.SessionManager.java

public SessionManager() {
    super();/*from www  .  jav a  2s  . c o  m*/
    AuthType type = AuthType.valueOf(CatPropertyProvider.INST.getProperty("CAT_AUTH_TYPE", "ADMIN_PWD"));
    switch (type) {
    case NOP:
        tokenCreator = new Function<Credential, Token>() {
            @Override
            public Token apply(Credential credential) {
                String account = credential.getAccount();
                return new Token(account, account);
            }
        };
        break;
    case LDAP:
        final String ldapUrl = CatPropertyProvider.INST.getProperty("CAT_LDAP_URL", null);
        if (StringUtils.isBlank(ldapUrl)) {
            throw new IllegalArgumentException("required CAT_LDAP_URL");
        }
        final String userDnTpl = CatPropertyProvider.INST.getProperty("CAT_LDAP_USER_DN_TPL", null);
        if (StringUtils.isBlank(userDnTpl)) {
            throw new IllegalArgumentException("required CAT_LDAP_USER_DN_TPL");
        }
        final String userDisplayAttr = CatPropertyProvider.INST.getProperty("CAT_LDAP_USER_DISPLAY_ATTR", null);
        final Pattern pattern = Pattern.compile("\\{0}");
        final Matcher userDnTplMatcher = pattern.matcher(userDnTpl);
        final String[] attrs = userDisplayAttr == null ? null : new String[] { userDisplayAttr };
        tokenCreator = new Function<Credential, Token>() {
            @Override
            public Token apply(Credential credential) {
                final String account = credential.getAccount();
                final String pwd = credential.getPassword();
                if (StringUtils.isEmpty(account) || StringUtils.isEmpty(pwd)) {
                    return null;
                }
                Hashtable<String, String> env = new Hashtable<String, String>();
                env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
                env.put(Context.PROVIDER_URL, ldapUrl);// LDAP server
                String userDn = userDnTplMatcher.replaceAll(account);
                env.put(Context.SECURITY_PRINCIPAL, pwd);
                env.put(Context.SECURITY_CREDENTIALS, pwd);
                try {
                    InitialLdapContext context = new InitialLdapContext(env, null);
                    final String baseDn = context.getNameInNamespace();
                    if (userDn.endsWith(baseDn)) {
                        userDn = userDn.substring(0, userDn.length() - baseDn.length() - 1);
                    }
                    String displayName = null;
                    if (attrs != null) {
                        final Attributes attributes = context.getAttributes(userDn, attrs);
                        if (attributes.size() > 0) {
                            displayName = attributes.getAll().next().get().toString();
                        }
                    }

                    return new Token(account, displayName == null ? account : displayName);
                } catch (Exception e) {
                    Cat.logError(e);
                    return null;
                }
            }

        };
        break;
    case ADMIN_PWD:
        final String p = CatPropertyProvider.INST.getProperty("CAT_ADMIN_PWD", "admin");

        tokenCreator = new Function<Credential, Token>() {
            @Override
            public Token apply(Credential credential) {
                String account = credential.getAccount();

                if ("admin".equals(account) && p.equals(credential.getPassword())) {
                    return new Token(account, account);
                }
                return null;
            }

        };
        break;
    }
}

From source file:no.feide.moria.directory.backend.JNDIBackend.java

/**
 * Authenticates the user using the supplied credentials and retrieves the
 * requested attributes./*from   w ww  .j  a  v  a2s.  c o  m*/
 * @param userCredentials
 *            User's credentials. Cannot be <code>null</code>.
 * @param attributeRequest
 *            Requested attributes.
 * @return The requested attributes (<code>String</code> names and
 *         <code>String[]</code> values), if they did exist in the
 *         external backend. Otherwise returns those attributes that could
 *         actually be read, this may be an empty <code>HashMap</code>.
 *         Returns an empty <code>HashMap</code> if
 *         <code>attributeRequest</code> is <code>null</code> or an
 *         empty array.
 * @throws AuthenticationFailedException
 *             If the authentication fails.
 * @throws BackendException
 *             If there is a problem accessing the backend.
 * @throws IllegalArgumentException
 *             If <code>userCredentials</code> is <code>null</code>.
 */
public final HashMap<String, String[]> authenticate(final Credentials userCredentials,
        final String[] attributeRequest) throws AuthenticationFailedException, BackendException {

    // Sanity check.
    if (userCredentials == null)
        throw new IllegalArgumentException("Credentials cannot be NULL");

    // Go through all references.
    for (int i = 0; i < myReferences.length; i++) {
        final String[] references = myReferences[i].getReferences();
        final String[] usernames = myReferences[i].getUsernames();
        final String[] passwords = myReferences[i].getPasswords();
        for (int j = 0; j < references.length; j++) {

            // For the benefit of the finally block below.
            InitialLdapContext ldap = null;

            try {

                // Context for this reference.
                try {
                    ldap = connect(references[j]);
                } catch (NamingException e) {
                    // Connection failed, but we might have other sources.
                    log.logWarn("Unable to access the backend on '" + references[j] + "': "
                            + e.getClass().getName(), mySessionTicket, e);
                    continue;
                }

                // Skip search phase if the reference(s) are explicit.
                String rdn = "";
                if (myReferences[i].isExplicitlyIndexed()) {

                    // Add the explicit reference; no search phase, no RDN.
                    ldap.addToEnvironment(Context.SECURITY_PRINCIPAL,
                            references[j].substring(references[j].lastIndexOf('/') + 1));

                } else {

                    // Anonymous search or not?
                    ldap.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
                    if ((usernames[j].length() == 0) && (passwords[j].length() > 0))
                        log.logWarn(
                                "Search username is empty but search password is not - possible index problem",
                                mySessionTicket);
                    else if ((passwords[j].length() == 0) && (usernames[j].length() > 0))
                        log.logWarn(
                                "Search password is empty but search username is not - possible index problem",
                                mySessionTicket);
                    else if ((passwords[j].length() == 0) && (usernames[j].length() == 0)) {
                        log.logDebug("Anonymous search for user element DN on " + references[j],
                                mySessionTicket);
                        ldap.removeFromEnvironment(Context.SECURITY_AUTHENTICATION);
                    } else
                        log.logDebug("Non-anonymous search for user element DN on " + references[j],
                                mySessionTicket);
                    ldap.addToEnvironment(Context.SECURITY_PRINCIPAL, usernames[j]);
                    ldap.addToEnvironment(Context.SECURITY_CREDENTIALS, passwords[j]);

                    // Search using the implicit reference.
                    String pattern = usernameAttribute + '=' + userCredentials.getUsername();
                    rdn = ldapSearch(ldap, pattern);
                    if (rdn == null) {

                        // No user element found. Try to guess the RDN.
                        rdn = userCredentials.getUsername();
                        rdn = guessedAttribute + '=' + rdn.substring(0, rdn.indexOf('@'));
                        log.logDebug("No subtree match for " + pattern + " on " + references[j]
                                + " - guessing on RDN " + rdn, mySessionTicket);

                    } else
                        log.logDebug("Matched " + pattern + " to " + rdn + ',' + ldap.getNameInNamespace(),
                                mySessionTicket);
                    ldap.addToEnvironment(Context.SECURITY_PRINCIPAL, rdn + ',' + ldap.getNameInNamespace());
                }

                // Authenticate and get attributes.
                ldap.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
                ldap.addToEnvironment(Context.SECURITY_CREDENTIALS, userCredentials.getPassword());
                try {
                    ldap.reconnect(null);
                    log.logDebug("Successfully authenticated " + userCredentials.getUsername() + " on "
                            + references[j], mySessionTicket);
                    return getAttributes(ldap, rdn, attributeRequest); // Success.
                } catch (AuthenticationException e) {

                    // Authentication failed, but we may have other
                    // references.
                    log.logDebug("Failed to authenticate user " + userCredentials.getUsername() + " on "
                            + references[j] + " - authentication failed", mySessionTicket);
                    continue;

                } catch (AuthenticationNotSupportedException e) {

                    // Password authentication not supported for the DN.
                    // We may still have other references.
                    log.logDebug("Failed to authenticate user " + userCredentials.getUsername() + " on "
                            + references[j] + " - authentication not supported", mySessionTicket);
                    continue;

                }

            } catch (ConfigurationException e) {
                throw new BackendException("Backend configuration problem with " + references[j], e);
            } catch (NamingException e) {
                throw new BackendException("Unable to access the backend on " + references[j], e);
            } finally {

                // Close the LDAP connection.
                if (ldap != null) {
                    try {
                        ldap.close();
                    } catch (NamingException e) {
                        // Ignored.
                        log.logWarn(
                                "Unable to close the backend connection to " + references[j] + " - ignoring",
                                mySessionTicket, e);
                    }
                }
            }

        }
    }

    // No user was found.
    throw new AuthenticationFailedException(
            "Failed to authenticate user " + userCredentials.getUsername() + " - no user found");

}