Example usage for javax.naming Context REFERRAL

List of usage examples for javax.naming Context REFERRAL

Introduction

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

Prototype

String REFERRAL

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

Click Source Link

Document

Constant that holds the name of the environment property for specifying how referrals encountered by the service provider are to be processed.

Usage

From source file:org.jsecurity.realm.ldap.DefaultLdapContextFactory.java

public LdapContext getLdapContext(String username, String password) throws NamingException {
    if (searchBase == null) {
        throw new IllegalStateException("A search base must be specified.");
    }//from ww  w  .jav a 2  s .c  o  m
    if (url == null) {
        throw new IllegalStateException("An LDAP URL must be specified of the form ldap://<hostname>:<port>");
    }

    if (username != null && principalSuffix != null) {
        username += principalSuffix;
    }

    Hashtable<String, String> env = new Hashtable<String, String>();

    env.put(Context.SECURITY_AUTHENTICATION, authentication);
    if (username != null) {
        env.put(Context.SECURITY_PRINCIPAL, username);
    }
    if (password != null) {
        env.put(Context.SECURITY_CREDENTIALS, password);
    }
    env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactoryClassName);
    env.put(Context.PROVIDER_URL, url);
    env.put(Context.REFERRAL, referral);

    // Only pool connections for system contexts
    if (usePooling && username != null && username.equals(systemUsername)) {
        // Enable connection pooling
        env.put(SUN_CONNECTION_POOLING_PROPERTY, "true");
    }

    if (additionalEnvironment != null) {
        env.putAll(additionalEnvironment);
    }

    if (log.isDebugEnabled()) {
        log.debug("Initializing LDAP context using URL [" + url + "] and username [" + systemUsername + "] "
                + "with pooling [" + (usePooling ? "enabled" : "disabled") + "]");
    }

    return new InitialLdapContext(env, null);
}

From source file:org.mule.module.ldap.api.jndi.LDAPJNDIConnection.java

/**
 * @param dn/*from w w w  .j a v a  2 s .  c o m*/
 * @param password
 * @return
 * @throws LDAPException
 */
private Hashtable<String, String> buildEnvironment(String dn, String password) throws LDAPException {
    Hashtable<String, String> env = new Hashtable<String, String>();

    env.put(Context.REFERRAL, getReferral());
    env.put(Context.SECURITY_AUTHENTICATION, getAuthentication());
    if (!isNoAuthentication()) {
        env.put(Context.SECURITY_PRINCIPAL, dn);
        env.put(Context.SECURITY_CREDENTIALS, password);
    }
    env.put(Context.INITIAL_CONTEXT_FACTORY, getInitialContextFactory());
    env.put(Context.PROVIDER_URL, getProviderUrl());

    if (isConnectionPoolEnabled()) {
        env.put(POOL_ENABLED_ENV_PARAM, "true");

        env.put(AUTHENTICATION_ENV_PARAM, getAuthentication());

        if (getMaxPoolConnections() > 0) {
            env.put(MAX_POOL_SIZE_ENV_PARAM, String.valueOf(getMaxPoolConnections()));
        }

        if (getInitialPoolSizeConnections() > 0) {
            env.put(INIT_POOL_SIZE_ENV_PARAM, String.valueOf(getInitialPoolSizeConnections()));
        }

        if (getPoolTimeout() > 0) {
            env.put(TIME_OUT_ENV_PARAM, String.valueOf(getPoolTimeout()));
        }
    } else {
        env.put(POOL_ENABLED_ENV_PARAM, "false");
    }

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

    return env;

}

From source file:org.nuxeo.ecm.directory.ldap.LDAPDirectory.java

/**
 * @return connection parameters to use for all LDAP queries
 *//*ww w  .  java2s. co  m*/
protected Properties computeContextProperties() throws DirectoryException {
    LDAPDirectoryDescriptor ldapDirectoryDesc = getDescriptor();
    // Initialization of LDAP connection parameters from parameters
    // registered in the LDAP "server" extension point
    Properties props = new Properties();
    LDAPServerDescriptor serverConfig = getServer();

    if (null == serverConfig) {
        throw new DirectoryException(
                "LDAP server configuration not found: " + ldapDirectoryDesc.getServerName());
    }

    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    /*
     * Get initial connection URLs, dynamic URLs may cause the list to be updated when creating the session
     */
    String ldapUrls = serverConfig.getLdapUrls();
    if (ldapUrls == null) {
        throw new DirectoryException("Server LDAP URL configuration is missing for directory " + getName());
    }
    props.put(Context.PROVIDER_URL, ldapUrls);

    // define how referrals are handled
    if (!getDescriptor().getFollowReferrals()) {
        props.put(Context.REFERRAL, "ignore");
    } else {
        // this is the default mode
        props.put(Context.REFERRAL, "follow");
    }

    /*
     * SSL Connections do not work with connection timeout property
     */
    if (serverConfig.getConnectionTimeout() > -1) {
        if (!serverConfig.useSsl()) {
            props.put("com.sun.jndi.ldap.connect.timeout",
                    Integer.toString(serverConfig.getConnectionTimeout()));
        } else {
            log.warn("SSL connections do not operate correctly"
                    + " when used with the connection timeout parameter, disabling timout");
        }
    }

    String bindDn = serverConfig.getBindDn();
    if (bindDn != null) {
        // Authenticated connection
        props.put(Context.SECURITY_PRINCIPAL, bindDn);
        props.put(Context.SECURITY_CREDENTIALS, serverConfig.getBindPassword());
    }

    if (serverConfig.isPoolingEnabled()) {
        // Enable connection pooling
        props.put("com.sun.jndi.ldap.connect.pool", "true");
        props.put("com.sun.jndi.ldap.connect.pool.protocol", "plain ssl");
        props.put("com.sun.jndi.ldap.connect.pool.authentication", "none simple DIGEST-MD5");
        props.put("com.sun.jndi.ldap.connect.pool.timeout", "1800000"); // 30
        // min
    }

    if (!serverConfig.isVerifyServerCert() && serverConfig.useSsl) {
        props.put("java.naming.ldap.factory.socket",
                "org.nuxeo.ecm.directory.ldap.LDAPDirectory$TrustingSSLSocketFactory");
    }

    return props;
}

From source file:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java

/**
 * Creates the directory context configuration.
 * //from   ww  w . jav a 2s.  c om
 * @param loginId
 *            the user principal ID to use when establishing the connection
 * @param loginPassword
 *            the password credentials to use when establishing the connection
 * @param isConnectionRetry
 *            if true, the alternate URL will be employed
 * @return Hashtable<String,String>
 */
protected Hashtable<String, String> getDirectoryContextEnvironment(String loginId, String loginPassword,
        boolean isConnectionRetry) {
    Hashtable<String, String> env = new Hashtable<String, String>();

    env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);

    if (!isConnectionRetry) {
        env.put(Context.PROVIDER_URL, connectionUrl);

    } else if (alternateUrl != null) {
        env.put(Context.PROVIDER_URL, alternateUrl);
    }
    if (loginId != null) {
        env.put(Context.SECURITY_PRINCIPAL, loginId);
    }
    if (loginPassword != null) {
        env.put(Context.SECURITY_CREDENTIALS, loginPassword);
    }
    if (securityAuthentication != null) {
        env.put(Context.SECURITY_AUTHENTICATION, securityAuthentication);
    }
    if (connectionProtocol != null) {
        env.put(Context.SECURITY_PROTOCOL, connectionProtocol);
    }
    if (referralStrategy != null) {
        env.put(Context.REFERRAL, referralStrategy);
    }
    if (connectionTimeout > 0) {
        env.put("com.sun.jndi.ldap.connect.timeout", connectionTimeout + "");
    }
    return env;
}

From source file:org.orbeon.oxf.processor.LDAPProcessor.java

private DirContext connect(Config config) {
    try {//from  w ww.j av a2  s .  com
        Properties env = new Properties();

        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, config.getBindDN());
        env.put(Context.SECURITY_CREDENTIALS, config.getPassword());
        env.put(LDAP_VERSION, DEFAULT_LDAP_VERSION);
        env.put(Context.INITIAL_CONTEXT_FACTORY, DEFAULT_CTX);
        env.put(Context.PROVIDER_URL, "ldap://" + config.getHost() + ":" + config.getPort());
        if (config.getReferral() != null) {
            env.put(Context.REFERRAL, config.getReferral());
        }

        if (config.getProtocol() != null)
            env.put(Context.SECURITY_PROTOCOL, config.getProtocol());
        env.put("com.sun.jndi.ldap.connect.pool", "true");

        return new InitialDirContext(env);
    } catch (NamingException e) {
        throw new OXFException("LDAP connect Failed", e);
    }
}

From source file:org.rhq.enterprise.server.core.jaas.LdapLoginModule.java

/**
 * Load a default set of properties to use when connecting to the LDAP server. If basic authentication is needed,
 * the caller must set Context.SECURITY_PRINCIPAL, Context.SECURITY_CREDENTIALS and Context.SECURITY_AUTHENTICATION
 * appropriately./*from w w  w  . j  av  a2s  .  c  om*/
 *
 * @return properties that are to be used when connecting to LDAP server
 */
private Properties getProperties() {
    Properties env = new Properties();

    // Map all user options into into our environment
    Iterator iter = options.entrySet().iterator();
    while (iter.hasNext()) {
        Entry entry = (Entry) iter.next();
        if ((entry.getKey() != null) && (entry.getValue() != null)) {
            env.put(entry.getKey(), entry.getValue());
        }
    }

    // Set our default factory name if one is not given
    String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY);
    if (factoryName == null) {
        env.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    }

    // Setup SSL if requested
    String protocol = env.getProperty(Context.SECURITY_PROTOCOL);
    if ("ssl".equals(protocol)) {
        String ldapSocketFactory = env.getProperty("java.naming.ldap.factory.socket");
        if (ldapSocketFactory == null) {
            env.put("java.naming.ldap.factory.socket", UntrustedSSLSocketFactory.class.getName());
        }
        env.put(Context.SECURITY_PROTOCOL, "ssl");
    }

    // Set the LDAP url
    String providerUrl = env.getProperty(Context.PROVIDER_URL);
    if (providerUrl == null) {
        providerUrl = "ldap://localhost:" + (((protocol != null) && protocol.equals("ssl")) ? "636" : "389");
    }

    env.setProperty(Context.PROVIDER_URL, providerUrl);

    // Follow referrals automatically
    env.setProperty(Context.REFERRAL, "ignore");//BZ:582471- active directory query change

    return env;
}

From source file:org.rhq.enterprise.server.resource.group.LdapGroupManagerBean.java

/**
 * Load a default set of properties to use when connecting to the LDAP server. If basic authentication is needed,
 * the caller must set Context.SECURITY_PRINCIPAL, Context.SECURITY_CREDENTIALS and Context.SECURITY_AUTHENTICATION
 * appropriately./*w  w w  .  j  a  v  a  2  s  . c o m*/
 *
 * @return properties that are to be used when connecting to LDAP server
 */
private Properties getProperties(Properties systemConfig) {
    Properties env = new Properties(systemConfig);
    // Set our default factory name if one is not given
    String factoryName = env.getProperty(RHQConstants.LDAPFactory);
    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryName);

    // Setup SSL if requested
    String value = env.getProperty(SystemSetting.USE_SSL_FOR_LDAP.getInternalName());
    boolean ldapSsl = "ssl".equalsIgnoreCase(value);
    if (ldapSsl) {
        String ldapSocketFactory = env.getProperty("java.naming.ldap.factory.socket");
        if (ldapSocketFactory == null) {
            env.put("java.naming.ldap.factory.socket", UntrustedSSLSocketFactory.class.getName());
        }
        env.put(Context.SECURITY_PROTOCOL, "ssl");
    }

    // Set the LDAP url
    String providerUrl = env.getProperty(RHQConstants.LDAPUrl);
    if (providerUrl == null) {
        int port = (ldapSsl) ? 636 : 389;
        providerUrl = "ldap://localhost:" + port;
    }

    env.setProperty(Context.PROVIDER_URL, providerUrl);

    // Follow referrals automatically
    env.setProperty(Context.REFERRAL, "ignore"); //BZ:582471- active directory query change

    return env;
}

From source file:org.sipfoundry.sipxconfig.bulk.ldap.LdapConnectionParams.java

public void applyToContext(LdapContextSource config) {
    config.setUserName(defaultString(m_principal, EMPTY));
    config.setPassword(defaultString(m_secret, EMPTY));
    config.setUrl(getUrl());/*from w w w. j av  a2s  . c om*/
    Map<String, String> otherParams = new HashMap<String, String>();
    otherParams.put(Context.REFERRAL, m_referral);
    config.setBaseEnvironmentProperties(otherParams);
}

From source file:org.sonar.plugins.ldap.LdapContextFactory.java

private InitialDirContext createInitialDirContext(String principal, String credentials, boolean pooling)
        throws NamingException {
    final InitialLdapContext ctx;
    if (startTLS) {
        // Note that pooling is not enabled for such connections, because "Stop TLS" is not performed.
        Properties env = new Properties();
        env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
        env.put(Context.PROVIDER_URL, providerUrl);
        env.put(Context.REFERRAL, DEFAULT_REFERRAL);
        // At this point env should not contain properties SECURITY_AUTHENTICATION, SECURITY_PRINCIPAL and SECURITY_CREDENTIALS to avoid "bind" operation prior to StartTLS:
        ctx = new InitialLdapContext(env, null);
        // http://docs.oracle.com/javase/jndi/tutorial/ldap/ext/starttls.html
        StartTlsResponse tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
        try {/*  w  w w.jav a 2 s  .  c o  m*/
            tls.negotiate();
        } catch (IOException e) {
            NamingException ex = new NamingException("StartTLS failed");
            ex.initCause(e);
            throw ex;
        }
        // Explicitly initiate "bind" operation:
        ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, authentication);
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, principal);
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials);
        ctx.reconnect(null);
    } else {
        ctx = new InitialLdapContext(getEnvironment(principal, credentials, pooling), null);
    }
    return ctx;
}

From source file:org.sonar.plugins.ldap.LdapContextFactory.java

private InitialDirContext createInitialDirContextUsingGssapi(String principal, String credentials)
        throws NamingException {
    Configuration.setConfiguration(new Krb5LoginConfiguration());
    InitialDirContext initialDirContext;
    try {/*from   w  w  w  .  j a  v a 2s  . c  o  m*/
        LoginContext lc = new LoginContext(getClass().getName(),
                new CallbackHandlerImpl(principal, credentials));
        lc.login();
        initialDirContext = Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<InitialDirContext>() {
            @Override
            public InitialDirContext run() throws NamingException {
                Properties env = new Properties();
                env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
                env.put(Context.PROVIDER_URL, providerUrl);
                env.put(Context.REFERRAL, DEFAULT_REFERRAL);
                return new InitialLdapContext(env, null);
            }
        });
    } catch (LoginException | PrivilegedActionException e) {
        NamingException namingException = new NamingException(e.getMessage());
        namingException.initCause(e);
        throw namingException;
    }
    return initialDirContext;
}