Example usage for javax.naming Context SECURITY_PROTOCOL

List of usage examples for javax.naming Context SECURITY_PROTOCOL

Introduction

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

Prototype

String SECURITY_PROTOCOL

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

Click Source Link

Document

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

Usage

From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java

/**
 * Reads JNDI connection information from the configuration.
 * <br>// w  w w.  j av  a  2s  . c  o  m
 * Creates an <code>Hashtable</code> containing the JNDI environment variables.
 * @param oConfigurationManager The configuration manager
 * @param eConfig the configuration section
 * @return <code>DirContext</code> that contains the JNDI connection
 * @throws UserException if configuration reading fails
 */
private Hashtable<String, String> readJNDIContext(IConfigurationManager oConfigurationManager, Element eConfig)
        throws UserException {
    Hashtable<String, String> htEnvironment = new Hashtable<String, String>();

    try {
        Element eSecurityPrincipal = oConfigurationManager.getSection(eConfig, "security_principal");
        if (eSecurityPrincipal == null) {
            _logger.error("No 'security_principal' section found in 'resource' configuration");
            throw new UserException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sPrincipal = oConfigurationManager.getParam(eSecurityPrincipal, "dn");
        if (sPrincipal == null) {
            _logger.error("No item 'dn' item found in configuration");
            throw new UserException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sPassword = oConfigurationManager.getParam(eSecurityPrincipal, "password");
        if (sPassword == null) {
            _logger.error("No 'password' item found in configuration ");
            throw new UserException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sDriver = oConfigurationManager.getParam(eConfig, "driver");
        if (sDriver == null) {
            _logger.error("No 'driver' item found in configuration");
            throw new UserException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sUrl = oConfigurationManager.getParam(eConfig, "url");
        if (sUrl == null) {
            _logger.error("No valid config item 'url' found in configuration");
            throw new UserException(SystemErrors.ERROR_CONFIG_READ);
        }

        if (sUrl.length() >= 5 && sUrl.substring(0, 5).equalsIgnoreCase("ldaps")) {
            // Request SSL transport
            htEnvironment.put(Context.SECURITY_PROTOCOL, "ssl");
            _logger.info("SSL enabled");
        } else {
            _logger.info("SSL disabled");
        }

        htEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, sDriver);
        htEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple");
        htEnvironment.put(Context.SECURITY_PRINCIPAL, sPrincipal);
        htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword);
        htEnvironment.put(Context.PROVIDER_URL, sUrl);

    } catch (UserException e) {
        throw e;
    } catch (Exception e) {
        _logger.error("Could not create a connection", e);
        throw new UserException(SystemErrors.ERROR_INTERNAL, e);
    }
    return htEnvironment;
}

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.LDAPInitialDirContextFactoryImpl.java

protected boolean isSSLSocketFactoryRequired(final Map<String, String> config) {
    boolean result = false;
    // Check for LDAPS config
    final String protocol = config.get(Context.SECURITY_PROTOCOL);
    if (protocol != null && protocol.equals(PROTOCOL_SSL)) {
        if (this.trustStoreType != null && this.trustStorePath != null && this.trustStorePassPhrase != null) {
            result = true;//from ww w.  j  a v a2 s.  c  o m
        } else {
            LOGGER.warn("The SSL configuration for LDAPS is not full, the default configuration will be used.");
        }
    }
    return result;
}

From source file:de.sub.goobi.helper.ldap.Ldap.java

private Hashtable<String, String> getLdapConnectionSettings() {
    // Set up environment for creating initial context
    Hashtable<String, String> env = new Hashtable<>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ConfigCore.getParameter("ldap_url"));
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    /* wenn die Verbindung ber ssl laufen soll */
    if (ConfigCore.getBooleanParameter("ldap_sslconnection")) {
        String keystorepath = ConfigCore.getParameter("ldap_keystore");
        String keystorepasswd = ConfigCore.getParameter("ldap_keystore_password");

        // add all necessary certificates first
        loadCertificates(keystorepath, keystorepasswd);

        // set properties, so that the current keystore is used for SSL
        System.setProperty("javax.net.ssl.keyStore", keystorepath);
        System.setProperty("javax.net.ssl.trustStore", keystorepath);
        System.setProperty("javax.net.ssl.keyStorePassword", keystorepasswd);
        env.put(Context.SECURITY_PROTOCOL, "ssl");
    }/*from w  w  w  . j  a va2  s .c o  m*/
    return env;
}

From source file:com.adito.activedirectory.ActiveDirectoryUserDatabaseConfiguration.java

public InitialLdapContext getInitialContext(String url, Map<String, String> properties) throws NamingException {
    Hashtable<String, String> variables = new Hashtable<String, String>(properties);
    variables.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    variables.put(Context.PROVIDER_URL, url); // Must use fully qualified hostname

    if (isSslProtcolType()) {
        variables.put("java.naming.ldap.factory.socket", "com.adito.boot.CustomSSLSocketFactory");
        // Add the custom socket factory
    }//from   ww w. j  a  va 2s.  com

    if (isFollowReferrals()) {
        variables.put(Context.REFERRAL, "follow");
    }

    variables.put("com.sun.jndi.ldap.connect.timeout", String.valueOf(getTimeout()));
    variables.put("java.naming.ldap.version", "3");
    variables.put("com.sun.jndi.ldap.connect.pool", "true");
    variables.put("javax.security.sasl.qop", "auth-conf,auth-int,auth");
    variables.put(Context.SECURITY_PROTOCOL, getProtocolType());

    InitialLdapContext context = new InitialLdapContext(variables, null);
    String usedUrl = (String) context.getEnvironment().get(Context.PROVIDER_URL);
    setLastContactedActiveDirectoryUrl(usedUrl);
    return context;
}

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() + "]");
        }/*w  w w .j  a v  a  2s. 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:no.feide.moria.directory.backend.JNDIBackend.java

/**
 * Protected constructor. Creates an initial default context environment and
 * adds support for referrals, a fix for OpenSSL aliases, and enables SSL as
 * default.//from  www  . j  a v  a  2  s  .c o m
 * @param sessionTicket
 *            The session ticket for this instance, used when logging. May
 *            be <code>null</code> (which is treated as an empty string)
 *            or an empty string.
 * @param timeout
 *            The number of seconds before a connection attempt through this
 *            backend times out.
 * @param ssl
 *            <code>true</code> if SSL is to be used, otherwise
 *            <code>false</code>.
 * @param usernameAttributeName
 *            The name of the attribute holding the username. Cannot be
 *            <code>null</code>.
 * @param guessedAttributeName
 *            If we search but cannot find a user element (for example, if
 *            it is not searchable), we will guess that the (R)DN starts
 *            with the substring
 *            <code><i>guessedAttributeName</i>=<i>usernamePrefix</i></code>,
 *            where <code><i>usernamePrefix</i></code> is the part of the
 *            username preceding the 'at' character. Cannot be
 *            <code>null</code>.
 * @throws IllegalArgumentException
 *             If <code>timeout</code> is less than zero.
 * @throws NullPointerException
 *             If <code>guessedAttributeName</code> or
 *             <code>usernameAttribute</code> is <code>null</code>.
 */
protected JNDIBackend(final String sessionTicket, final int timeout, final boolean ssl,
        final String usernameAttributeName, final String guessedAttributeName)
        throws IllegalArgumentException, NullPointerException {

    // Assignments, with sanity checks.
    if (usernameAttributeName == null)
        throw new NullPointerException("Username attribute name cannot be NULL");
    usernameAttribute = usernameAttributeName;
    if (guessedAttributeName == null)
        throw new NullPointerException("Guessed attribute name cannot be NULL");
    guessedAttribute = guessedAttributeName;
    if (timeout < 0)
        throw new IllegalArgumentException("Timeout must be greater than zero");
    myTimeout = timeout;
    mySessionTicket = sessionTicket;
    if (mySessionTicket == null)
        mySessionTicket = "";

    // Create initial context environment.
    defaultEnv = new Hashtable<String, String>();
    defaultEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    // To catch referrals.
    defaultEnv.put(Context.REFERRAL, "throw");

    // Due to OpenSSL problems.
    defaultEnv.put("java.naming.ldap.derefAliases", "never");

    // Use LDAP v3.
    defaultEnv.put("java.naming.ldap.version", "3");

    // Add timeout value for connection attempts (not searches).
    defaultEnv.put("com.sun.jndi.ldap.connect.timeout", String.valueOf(1000 * timeout));

    // Should we enable SSL?
    if (ssl)
        defaultEnv.put(Context.SECURITY_PROTOCOL, "ssl");

}

From source file:org.alfresco.repo.security.authentication.ldap.LDAPInitialDirContextFactoryImpl.java

/**
 * Check if it required to use custom SSL socket factory with custom trustStore.
 * <br>Required for LDAPS configuration. The <code>ldap.authentication.java.naming.security.protocol</code> should be set to "ssl" for LDAPS.
 * <br>The following properties should be set:
 * <ul>/*from ww  w .j a v a  2s.  c o  m*/
 * <li>ldap.authentication.truststore.path
 * <li>ldap.authentication.truststore.type
 * <li>ldap.authentication.truststore.passphrase
 * <li>ldap.authentication.java.naming.security.protocol
 * </ul>
 *
 * @return <code>true</code> if all the required properties are set
 */
private boolean isSSLSocketFactoryRequired() {
    boolean result = false;
    // Check for LDAPS config
    String protocol = authenticatedEnvironment.get(Context.SECURITY_PROTOCOL);
    if (protocol != null && protocol.equals("ssl")) {
        if (getTrustStoreType() != null && getTrustStorePath() != null && getTrustStoreType() != null) {
            result = true;
        } else {
            logger.warn("The SSL configuration for LDAPS is not full, the default configuration will be used.");
        }
    }
    return result;
}

From source file:org.apache.cloudstack.ldap.LdapContextFactory.java

private void enableSSL(final Hashtable<String, String> environment) {
    final boolean sslStatus = _ldapConfiguration.getSSLStatus();

    if (sslStatus) {
        s_logger.info("LDAP SSL enabled.");
        environment.put(Context.SECURITY_PROTOCOL, "ssl");
        System.setProperty("javax.net.ssl.trustStore", _ldapConfiguration.getTrustStore());
        System.setProperty("javax.net.ssl.trustStorePassword", _ldapConfiguration.getTrustStorePassword());
    }//from   w  ww. j a  v  a  2  s.c  o  m
}

From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java

private void doConnect(final StudioProgressMonitor monitor) throws NamingException {
    context = null;// www .  j a  v a 2s .co m
    isConnected = true;

    // setup connection parameters
    String host = connection.getConnectionParameter().getHost();
    int port = connection.getConnectionParameter().getPort();
    long timeout = connection.getConnectionParameter().getTimeout();

    useLdaps = connection.getConnectionParameter()
            .getEncryptionMethod() == ConnectionParameter.EncryptionMethod.LDAPS;
    useStartTLS = connection.getConnectionParameter()
            .getEncryptionMethod() == ConnectionParameter.EncryptionMethod.START_TLS;

    environment = new Hashtable<>();
    Preferences preferences = ConnectionCorePlugin.getDefault().getPluginPreferences();
    final boolean validateCertificates = preferences
            .getBoolean(ConnectionCoreConstants.PREFERENCE_VALIDATE_CERTIFICATES);
    String ldapCtxFactory = preferences.getString(ConnectionCoreConstants.PREFERENCE_LDAP_CONTEXT_FACTORY);
    environment.put(Context.INITIAL_CONTEXT_FACTORY, ldapCtxFactory);
    environment.put(JAVA_NAMING_LDAP_VERSION, "3"); //$NON-NLS-1$

    // timeouts
    /*
     *  Don't use a timeout when using ldaps: JNDI throws a SocketException  when setting a timeout on SSL connections.
     *  See https://bugs.openjdk.java.net/browse/JDK-8173451
     */
    if (!useLdaps) {
        if (timeout < 0) {
            timeout = 0;
        }
        environment.put(COM_SUN_JNDI_LDAP_CONNECT_TIMEOUT, Long.toString(timeout)); //$NON-NLS-1$
    }

    environment.put(COM_SUN_JNDI_DNS_TIMEOUT_INITIAL, "2000"); //$NON-NLS-1$
    environment.put(COM_SUN_JNDI_DNS_TIMEOUT_RETRIES, "3"); //$NON-NLS-1$

    // ldaps://
    if (useLdaps) {
        environment.put(Context.PROVIDER_URL, LdapUrl.LDAPS_SCHEME + host + ':' + port);
        environment.put(Context.SECURITY_PROTOCOL, "ssl"); //$NON-NLS-1$
        // host name verification is done in StudioTrustManager
        environment.put(JAVA_NAMING_LDAP_FACTORY_SOCKET,
                validateCertificates ? StudioSSLSocketFactory.class.getName()
                        : DummySSLSocketFactory.class.getName());
    } else {
        environment.put(Context.PROVIDER_URL, LdapUrl.LDAP_SCHEME + host + ':' + port);
    }

    if (binaryAttributes != null) {
        setBinaryAttributes(binaryAttributes);
    }

    InnerRunnable runnable = new InnerRunnable() {
        public void run() {
            try {
                context = new InitialLdapContext(environment, null);

                if (useStartTLS) {
                    try {
                        StartTlsResponse tls = (StartTlsResponse) context
                                .extendedOperation(new StartTlsRequest());
                        // deactivate host name verification at this level,
                        // host name verification is done in StudioTrustManager
                        tls.setHostnameVerifier((hostname, session) -> true);

                        if (validateCertificates) {
                            tls.negotiate(StudioSSLSocketFactory.getDefault());
                        } else {
                            tls.negotiate(DummySSLSocketFactory.getDefault());
                        }
                    } catch (Exception e) {
                        namingException = new NamingException(e.getMessage() != null ? e.getMessage()
                                : "Error while establishing TLS session"); //$NON-NLS-1$
                        namingException.setRootCause(e);
                        context.close();
                    }
                }
            } catch (NamingException ne) {
                namingException = ne;
            }
        }
    };

    runAndMonitor(runnable, monitor);

    if (runnable.getException() != null) {
        throw runnable.getException();
    } else if (context != null) {
        // all OK
    } else {
        throw new NamingException("???"); //$NON-NLS-1$
    }
}

From source file:org.apache.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java

protected DirContext open() throws NamingException {
    if (context != null) {
        return context;
    }//from   w  ww.  j  av  a  2  s  . com
    try {
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
        if (connectionUsername != null || !"".equals(connectionUsername)) {
            env.put(Context.SECURITY_PRINCIPAL, connectionUsername);
        }
        if (connectionPassword != null || !"".equals(connectionPassword)) {
            env.put(Context.SECURITY_CREDENTIALS, connectionPassword);
        }
        env.put(Context.SECURITY_PROTOCOL, connectionProtocol == null ? "" : connectionProtocol);
        env.put(Context.PROVIDER_URL, connectionURL == null ? "" : connectionURL);
        env.put(Context.SECURITY_AUTHENTICATION, authentication == null ? "" : authentication);
        context = new InitialDirContext(env);

    } catch (NamingException e) {
        log.error(e);
        throw e;
    }
    return context;
}