Example usage for javax.naming Context SECURITY_AUTHENTICATION

List of usage examples for javax.naming Context SECURITY_AUTHENTICATION

Introduction

In this page you can find the example usage for javax.naming Context SECURITY_AUTHENTICATION.

Prototype

String SECURITY_AUTHENTICATION

To view the source code for javax.naming Context SECURITY_AUTHENTICATION.

Click Source Link

Document

Constant that holds the name of the environment property for specifying the security level to use.

Usage

From source file:nl.nn.adapterframework.jms.JNDIBase.java

protected Hashtable getJndiEnv() throws NamingException {
    Properties jndiEnv = new Properties();

    if (StringUtils.isNotEmpty(getJndiProperties())) {
        URL url = ClassUtils.getResourceURL(classLoader, getJndiProperties());
        if (url == null) {
            throw new NamingException("cannot find jndiProperties from [" + getJndiProperties() + "]");
        }/*from  w  ww  .ja va2  s  .c  o m*/
        try {
            jndiEnv.load(url.openStream());
        } catch (IOException e) {
            throw new NamingException("cannot load jndiProperties [" + getJndiProperties() + "] from url ["
                    + url.toString() + "]");
        }
    }
    if (getInitialContextFactoryName() != null)
        jndiEnv.put(Context.INITIAL_CONTEXT_FACTORY, getInitialContextFactoryName());
    if (getProviderURL() != null)
        jndiEnv.put(Context.PROVIDER_URL, getProviderURL());
    if (getAuthentication() != null)
        jndiEnv.put(Context.SECURITY_AUTHENTICATION, getAuthentication());
    if (getPrincipal() != null || getCredentials() != null || getJndiAuthAlias() != null) {
        CredentialFactory jndiCf = new CredentialFactory(getJndiAuthAlias(), getPrincipal(), getCredentials());
        if (StringUtils.isNotEmpty(jndiCf.getUsername()))
            jndiEnv.put(Context.SECURITY_PRINCIPAL, jndiCf.getUsername());
        if (StringUtils.isNotEmpty(jndiCf.getPassword()))
            jndiEnv.put(Context.SECURITY_CREDENTIALS, jndiCf.getPassword());
    }
    if (getUrlPkgPrefixes() != null)
        jndiEnv.put(Context.URL_PKG_PREFIXES, getUrlPkgPrefixes());
    if (getSecurityProtocol() != null)
        jndiEnv.put(Context.SECURITY_PROTOCOL, getSecurityProtocol());

    if (log.isDebugEnabled()) {
        for (Iterator it = jndiEnv.keySet().iterator(); it.hasNext();) {
            String key = (String) it.next();
            String value = jndiEnv.getProperty(key);
            log.debug("jndiEnv [" + key + "] = [" + value + "]");
        }
    }
    return jndiEnv;
}

From source file:nl.nn.adapterframework.ldap.LdapFindMemberPipe.java

private boolean findMember(String host, int port, String dnSearchIn, boolean useSsl, String dnFind,
        boolean recursiveSearch) throws NamingException {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    String provUrl = retrieveUrl(host, port, dnSearchIn, useSsl);
    env.put(Context.PROVIDER_URL, provUrl);
    if (StringUtils.isNotEmpty(cf.getUsername())) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, cf.getUsername());
        env.put(Context.SECURITY_CREDENTIALS, cf.getPassword());
    } else {/*  ww  w. j  a v  a 2  s .c  om*/
        env.put(Context.SECURITY_AUTHENTICATION, "none");
    }
    DirContext ctx = null;
    try {
        try {
            ctx = new InitialDirContext(env);
        } catch (CommunicationException e) {
            log.info("Cannot create constructor for DirContext (" + e.getMessage()
                    + "], will try again with dummy SocketFactory");
            env.put("java.naming.ldap.factory.socket", DummySSLSocketFactory.class.getName());
            ctx = new InitialLdapContext(env, null);
        }
        Attribute attrs = ctx.getAttributes("").get("member");
        if (attrs != null) {
            boolean found = false;
            for (int i = 0; i < attrs.size() && !found; i++) {
                String dnFound = (String) attrs.get(i);
                if (dnFound.equalsIgnoreCase(dnFind)) {
                    found = true;
                } else {
                    if (recursiveSearch) {
                        found = findMember(host, port, dnFound, useSsl, dnFind, recursiveSearch);
                    }
                }
            }
            return found;
        }
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.warn("Exception closing DirContext", e);
            }
        }
    }
    return false;
}

From source file:nl.nn.adapterframework.webcontrol.LoginFilter.java

private boolean checkUsernamePassword(String username, String password, String authorizePathMode) {
    String dnUser = Misc.replace(ldapAuthUserBase, "%UID%", username);

    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapAuthUrl);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, dnUser);
    env.put(Context.SECURITY_CREDENTIALS, password);

    DirContext ctx = null;/*w w  w. jav  a2s  .  c  o  m*/
    try {
        try {
            ctx = new InitialDirContext(env);
        } catch (CommunicationException e) {
            log.info("cannot create constructor for DirContext (" + e.getMessage()
                    + "], will try again with dummy SocketFactory");
            env.put("java.naming.ldap.factory.socket", DummySSLSocketFactory.class.getName());
            ctx = new InitialLdapContext(env, null);
        }

        if (authorizePathMode == null) {
            return true;
        } else {
            if (authorizePathMode.equals(AUTH_PATH_MODE_OBSERVER)) {
                if (isMemberOf(ctx, dnUser, ldapAuthObserverBase)) {
                    return true;
                }
                if (isMemberOf(ctx, dnUser, ldapAuthDataAdminBase)) {
                    return true;
                }
            }
            if (authorizePathMode.equals(AUTH_PATH_MODE_DATAADMIN)) {
                if (isMemberOf(ctx, dnUser, ldapAuthDataAdminBase)) {
                    return true;
                }
            }
            if (authorizePathMode.equals(AUTH_PATH_MODE_TESTER)) {
                if (isMemberOf(ctx, dnUser, ldapAuthTesterBase)) {
                    return true;
                }
            }
        }
    } catch (AuthenticationException e) {
        return false;
    } catch (Exception e) {
        log.warn("LoginFilter caught Exception", e);
        return false;
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                log.warn("LoginFilter caught Exception", e);
            }
        }
    }
    return false;
}

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

/**
 * Checks whether a user element exists, based on its username value.
 * @param username/*w w  w . j  a va2s. co  m*/
 *            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  av  a  2  s.  c  om
 * @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");

}

From source file:org.acegisecurity.ldap.DefaultInitialDirContextFactory.java

/**
 * Sets up the environment parameters for creating a new context.
 *
 * @return the Hashtable describing the base DirContext that will be created, minus the username/password if any.
 *//*from w  w  w.  j a  v a  2s  .  c  o m*/
protected Hashtable getEnvironment() {
    Hashtable env = new Hashtable();

    env.put(Context.SECURITY_AUTHENTICATION, authenticationType);
    env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
    env.put(Context.PROVIDER_URL, getProviderUrl());

    if (useConnectionPool) {
        env.put(CONNECTION_POOL_KEY, "true");
    }

    if ((extraEnvVars != null) && (extraEnvVars.size() > 0)) {
        env.putAll(extraEnvVars);
    }

    return env;
}

From source file:org.acegisecurity.ldap.DefaultInitialDirContextFactory.java

/**
 * Connects anonymously unless a manager user has been specified, in which case it will bind as the
 * manager.//  www  .  j a v  a2 s.c  om
 *
 * @return the resulting context object.
 */
public DirContext newInitialDirContext() {
    if (managerDn != null) {
        return newInitialDirContext(managerDn, managerPassword);
    }

    Hashtable env = getEnvironment();
    env.put(Context.SECURITY_AUTHENTICATION, AUTH_TYPE_NONE);

    return connect(env);
}

From source file:org.akaza.openclinica.controller.SystemController.java

public HashMap<String, Object> getLdapModule(StudyBean studyBean) {
    String enabled = CoreResources.getField("ldap.enabled");
    String ldapHost = CoreResources.getField("ldap.host");
    String username = CoreResources.getField("ldap.userDn");
    String password = CoreResources.getField("ldap.password");

    String result = "";
    Properties env = new Properties();

    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapHost);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, username); // replace with user DN
    env.put(Context.SECURITY_CREDENTIALS, password);

    DirContext ctx = null;/*from  www  .  j a va2s . c o m*/
    try {
        ctx = new InitialDirContext(env);
        result = "ACTIVE";
    } catch (Exception e) {
        result = "INACTIVE";
    }

    HashMap<String, String> mapMetadata = new HashMap<>();
    mapMetadata.put("ldap.host", ldapHost);

    HashMap<String, Object> mapWebService = new HashMap<>();
    mapWebService.put("enabled", enabled.equalsIgnoreCase("true") ? "True" : "False");
    mapWebService.put("status", result);
    mapWebService.put("metadata", mapMetadata);

    HashMap<String, Object> mapModule = new HashMap<>();
    mapModule.put("Ldap", mapWebService);

    return mapModule;
}

From source file:org.apache.activemq.artemis.tests.integration.amqp.SaslKrb5LDAPSecurityTest.java

@Test
public void testRunning() throws Exception {
    Hashtable<String, String> env = new Hashtable<>();
    env.put(Context.PROVIDER_URL, "ldap://localhost:1024");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, PRINCIPAL);
    env.put(Context.SECURITY_CREDENTIALS, CREDENTIALS);
    DirContext ctx = new InitialDirContext(env);

    HashSet<String> set = new HashSet<>();

    NamingEnumeration<NameClassPair> list = ctx.list("ou=system");

    while (list.hasMore()) {
        NameClassPair ncp = list.next();
        set.add(ncp.getName());/*from www .j ava 2  s .c  om*/
    }

    Assert.assertTrue(set.contains("uid=admin"));
    Assert.assertTrue(set.contains("ou=users"));
    Assert.assertTrue(set.contains("ou=groups"));
    Assert.assertTrue(set.contains("ou=configuration"));
    Assert.assertTrue(set.contains("prefNodeName=sysPrefRoot"));

    ctx.close();
}

From source file:org.apache.activemq.artemis.tests.integration.amqp.SaslKrb5LDAPSecurityTest.java

@Test
public void testSaslGssapiLdapAuth() throws Exception {

    final Hashtable<String, String> env = new Hashtable<>();
    env.put(Context.PROVIDER_URL, "ldap://localhost:1024");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");

    LoginContext loginContext = new LoginContext("broker-sasl-gssapi");
    loginContext.login();//from  w  ww.j ava 2s  .  c om
    try {
        Subject.doAs(loginContext.getSubject(), (PrivilegedExceptionAction<Object>) () -> {

            HashSet<String> set = new HashSet<>();

            DirContext ctx = new InitialDirContext(env);
            NamingEnumeration<NameClassPair> list = ctx.list("ou=system");

            while (list.hasMore()) {
                NameClassPair ncp = list.next();
                set.add(ncp.getName());
            }

            Assert.assertTrue(set.contains("uid=first"));
            Assert.assertTrue(set.contains("cn=users"));
            Assert.assertTrue(set.contains("ou=configuration"));
            Assert.assertTrue(set.contains("prefNodeName=sysPrefRoot"));

            ctx.close();
            return null;

        });
    } catch (PrivilegedActionException e) {
        throw e.getException();
    }
}