Example usage for javax.naming.ldap InitialLdapContext removeFromEnvironment

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

Introduction

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

Prototype

public Object removeFromEnvironment(String propName) throws NamingException 

Source Link

Usage

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

/**
 * Checks whether a user element exists, based on its username value.
 * @param username//  ww  w  .  ja v  a2 s .  c  om
 *            User name.
 * @return <code>true</code> if the user can be looked up through JNDI,
 *         otherwise <code>false</code>.
 * @throws BackendException
 *             If there is a problem accessing the backend.
 */
public final boolean userExists(final String username) throws BackendException {

    // Sanity checks.
    if ((username == null) || (username.length() == 0))
        return false;

    // The search pattern.
    String pattern = usernameAttribute + '=' + username;

    // Go through all references.
    InitialLdapContext ldap = null;
    for (int i = 0; i < myReferences.length; i++) {
        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++) {

            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]
                            + "' to verify existence of '" + username + "': " + e.getClass().getName(),
                            mySessionTicket, e);
                    continue;
                }

                // 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 to verify existence of '" + username + "' on "
                            + references[j], mySessionTicket);
                ldap.addToEnvironment(Context.SECURITY_PRINCIPAL, usernames[j]);
                ldap.addToEnvironment(Context.SECURITY_CREDENTIALS, passwords[j]);

                // Search this reference.
                if (ldapSearch(ldap, pattern) != null)
                    return true;

            } catch (NamingException e) {

                // Unable to connect, but we might have other sources.
                log.logWarn("Unable to access the backend on '" + references[j] + "' to verify existence of '"
                        + username + "': " + e.getClass().getName(), mySessionTicket, e);
                continue;

            } 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] + "': "
                                + e.getClass().getName(), mySessionTicket, e);
                    }
                }
            }

        }
    }

    // Still no match.
    return false;

}

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

/**
 * Authenticates the user using the supplied credentials and retrieves the
 * requested attributes.//from  w w w .  j a v a  2  s  .  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");

}