Example usage for javax.naming Context SECURITY_CREDENTIALS

List of usage examples for javax.naming Context SECURITY_CREDENTIALS

Introduction

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

Prototype

String SECURITY_CREDENTIALS

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

Click Source Link

Document

Constant that holds the name of the environment property for specifying the credentials of the principal for authenticating the caller to the service.

Usage

From source file:org.infoscoop.account.ldap.LDAPAccountManager.java

private DirContext initContext() throws NamingException {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    env.put(Context.PROVIDER_URL, this.connectionURL);
    env.put("java.naming.ldap.version", "3");
    if (this.connectionName != null) {
        env.put(Context.SECURITY_PRINCIPAL, this.connectionName);
        env.put(Context.SECURITY_CREDENTIALS, this.connectionPassword);
    }// ww  w . j  av a 2s . co  m
    return new InitialDirContext(env);
}

From source file:alpine.auth.LdapConnectionWrapper.java

/**
 * Asserts a users credentials. Returns an LdapContext if assertion is successful
 * or an exception for any other reason.
 *
 * @param userDn the users DN to assert/*from  w  ww .java2  s  . c o  m*/
 * @param password the password to assert
 * @return the LdapContext upon a successful connection
 * @throws NamingException when unable to establish a connection
 * @since 1.4.0
 */
public LdapContext createLdapContext(String userDn, String password) throws NamingException {
    if (StringUtils.isEmpty(userDn) || StringUtils.isEmpty(password)) {
        throw new NamingException("Username or password cannot be empty or null");
    }
    final Hashtable<String, String> env = new Hashtable<>();
    if (StringUtils.isNotBlank(LDAP_SECURITY_AUTH)) {
        env.put(Context.SECURITY_AUTHENTICATION, LDAP_SECURITY_AUTH);
    }
    env.put(Context.SECURITY_PRINCIPAL, userDn);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, LDAP_URL);
    if (IS_LDAP_SSLTLS) {
        env.put("java.naming.ldap.factory.socket", "alpine.crypto.RelaxedSSLSocketFactory");
    }
    try {
        return new InitialLdapContext(env, null);
    } catch (CommunicationException e) {
        LOGGER.error("Failed to connect to directory server", e);
        throw (e);
    } catch (NamingException e) {
        throw new NamingException("Failed to authenticate user");
    }
}

From source file:com.surevine.chat.auth.GroupAuthorisationFilter.java

protected InitialDirContext getLdapConnection() throws NamingException {
    Properties ldapEnv = new Properties();
    ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    ldapEnv.put(Context.PROVIDER_URL, "ldap://" + _host + "/" + _rootContext);
    ldapEnv.put(Context.SECURITY_PRINCIPAL, _rootDN);
    ldapEnv.put(Context.SECURITY_CREDENTIALS, _rootPW);
    return new InitialDirContext(ldapEnv);

}

From source file:org.eclipse.skalli.core.user.ldap.LDAPClient.java

private LdapContext getLdapContext() throws NamingException, AuthenticationException {
    if (config == null) {
        throw new NamingException("LDAP not configured");
    }/*w  w  w .jav  a 2s.  c om*/
    if (StringUtils.isBlank(config.getProviderUrl())) {
        throw new NamingException("No LDAP server available");
    }
    if (StringUtils.isBlank(config.getUsername()) || StringUtils.isBlank(config.getPassword())) {
        throw new AuthenticationException("No LDAP credentials available");
    }
    String ctxFactory = config.getCtxFactory();
    if (StringUtils.isBlank(ctxFactory)) {
        ctxFactory = DEFAULT_CONTEXT_FACTORY;
    }
    String authentication = config.getAuthentication();
    if (StringUtils.isBlank(authentication)) {
        authentication = SIMPLE_AUTHENTICATION;
    }

    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, ctxFactory);
    env.put(Context.PROVIDER_URL, config.getProviderUrl());
    env.put(Context.SECURITY_PRINCIPAL, config.getUsername());
    env.put(Context.SECURITY_CREDENTIALS, config.getPassword());
    env.put(Context.SECURITY_AUTHENTICATION, authentication);
    if (StringUtils.isNotBlank(config.getReferral())) {
        env.put(Context.REFERRAL, config.getReferral());
    }
    if (config.getProviderUrl().startsWith(LDAPS_SCHEME)) {
        env.put(Context.SECURITY_PROTOCOL, "ssl"); //$NON-NLS-1$
        if (config.isSslNoVerify()) {
            env.put(JNDI_SOCKET_FACTORY, LDAPTrustAllSocketFactory.class.getName());
        }
    }
    // Gemini-specific properties
    env.put(JNDIConstants.BUNDLE_CONTEXT, FrameworkUtil.getBundle(LDAPClient.class).getBundleContext());

    // com.sun.jndi.ldap.LdapCtxFactory specific properties
    env.put(READ_TIMEOUT, DEFAULT_READ_TIMEOUT);
    env.put(USE_CONNECTION_POOLING, "true"); //$NON-NLS-1$

    // extremly ugly classloading workaround:
    // com.sun.jndi.ldap.LdapCtxFactory uses Class.forName() to load the socket factory, shame on them!
    InitialLdapContext ctx = null;
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(LDAPTrustAllSocketFactory.class.getClassLoader());
        ctx = new InitialLdapContext(env, null);
    } finally {
        if (classloader != null) {
            Thread.currentThread().setContextClassLoader(classloader);
        }
    }
    return ctx;
}

From source file:com.mirth.connect.connectors.jms.JmsClient.java

private ConnectionFactory lookupConnectionFactoryWithJndi() throws Exception {
    String channelId = connector.getChannelId();
    String channelName = connector.getChannel().getName();

    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

    try {/*ww w . j  a v a 2 s . c om*/
        MirthContextFactory contextFactory = contextFactoryController.getContextFactory(resourceIds);
        Thread.currentThread().setContextClassLoader(contextFactory.getApplicationClassLoader());

        Hashtable<String, Object> env = new Hashtable<String, Object>();
        env.put(Context.PROVIDER_URL,
                replacer.replaceValues(connectorProperties.getJndiProviderUrl(), channelId, channelName));
        env.put(Context.INITIAL_CONTEXT_FACTORY, replacer
                .replaceValues(connectorProperties.getJndiInitialContextFactory(), channelId, channelName));
        env.put(Context.SECURITY_PRINCIPAL,
                replacer.replaceValues(connectorProperties.getUsername(), channelId, channelName));
        env.put(Context.SECURITY_CREDENTIALS,
                replacer.replaceValues(connectorProperties.getPassword(), channelId, channelName));

        initialContext = new InitialContext(env);
        String connectionFactoryName = replacer
                .replaceValues(connectorProperties.getJndiConnectionFactoryName(), channelId, channelName);
        return (ConnectionFactory) initialContext.lookup(connectionFactoryName);
    } finally {
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
}

From source file:org.wso2.carbon.user.core.ldap.LDAPConnectionContext.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public LDAPConnectionContext(RealmConfiguration realmConfig) throws UserStoreException {

    //if DNS is enabled, populate DC Map
    String DNSUrl = realmConfig.getUserStoreProperty(LDAPConstants.DNS_URL);
    if (DNSUrl != null) {
        DNSDomainName = realmConfig.getUserStoreProperty(LDAPConstants.DNS_DOMAIN_NAME);
        if (DNSDomainName == null) {
            throw new UserStoreException("DNS is enabled, but DNS domain name not provided.");
        } else {/*from  w  w  w  .ja v  a  2  s .c om*/
            environmentForDNS = new Hashtable();
            environmentForDNS.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
            environmentForDNS.put("java.naming.provider.url", DNSUrl);
            populateDCMap();
        }
        //need to keep track of if the user store config is read only
        String readOnlyString = realmConfig
                .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_READ_ONLY);
        if (readOnlyString != null) {
            readOnly = Boolean.parseBoolean(readOnlyString);
        }
    }

    String rawConnectionURL = realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_URL);
    String connectionURL = null;
    //if DNS enabled in AD case, this can be null
    if (rawConnectionURL != null) {
        String portInfo = rawConnectionURL.split(":")[2];

        String port = null;

        // if the port contains a template string that refers to carbon.xml
        if ((portInfo.contains("${")) && (portInfo.contains("}"))) {
            port = Integer.toString(CarbonUtils.getPortFromServerConfig(portInfo));
        }

        if (port != null) {
            connectionURL = rawConnectionURL.replace(portInfo, port);
        } else {
            // if embedded-ldap is not enabled,
            connectionURL = realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_URL);
        }
    }

    String connectionName = realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_NAME);
    String connectionPassword = realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_PASSWORD);

    if (log.isDebugEnabled()) {
        log.debug("Connection Name :: " + connectionName + ", Connection URL :: " + connectionURL);
    }

    environment = new Hashtable();

    environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    environment.put(Context.SECURITY_AUTHENTICATION, "simple");

    /**
     * In carbon JNDI context we need to by pass specific tenant context and we need the base
     * context for LDAP operations.
     */
    environment.put(CarbonConstants.REQUEST_BASE_CONTEXT, "true");

    if (connectionName != null) {
        environment.put(Context.SECURITY_PRINCIPAL, connectionName);
    }

    if (connectionPassword != null) {
        environment.put(Context.SECURITY_CREDENTIALS, connectionPassword);
    }

    if (connectionURL != null) {
        environment.put(Context.PROVIDER_URL, connectionURL);
    }

    // Enable connection pooling if property is set in user-mgt.xml
    boolean isLDAPConnectionPoolingEnabled = false;
    String value = realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_POOLING_ENABLED);

    if (value != null && !value.trim().isEmpty()) {
        isLDAPConnectionPoolingEnabled = Boolean.parseBoolean(value);
    }

    environment.put("com.sun.jndi.ldap.connect.pool", isLDAPConnectionPoolingEnabled ? "true" : "false");

    // set referral status if provided in configuration.
    if (realmConfig.getUserStoreProperty(LDAPConstants.PROPERTY_REFERRAL) != null) {
        environment.put("java.naming.referral",
                realmConfig.getUserStoreProperty(LDAPConstants.PROPERTY_REFERRAL));
    }

    String binaryAttribute = realmConfig.getUserStoreProperty(LDAPConstants.LDAP_ATTRIBUTES_BINARY);

    if (binaryAttribute != null) {
        environment.put(LDAPConstants.LDAP_ATTRIBUTES_BINARY, binaryAttribute);
    }

    //Set connect timeout if provided in configuration. Otherwise set default value
    String connectTimeout = realmConfig.getUserStoreProperty(CONNECTION_TIME_OUT);
    if (connectTimeout != null && !connectTimeout.trim().isEmpty()) {
        environment.put("com.sun.jndi.ldap.connect.timeout", connectTimeout);
    } else {
        environment.put("com.sun.jndi.ldap.connect.timeout", "5000");
    }
}

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  w w  .  j  ava2 s  .c  om
        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:org.picketlink.idm.performance.TestBase.java

public LdapContext getLdapContext() throws Exception {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, LDAP_PROVIDER_URL);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, LDAP_PRINCIPAL);
    env.put(Context.SECURITY_CREDENTIALS, LDAP_CREDENTIALS);

    return new InitialLdapContext(env, null);
}

From source file:org.dcm4che3.tool.dcmldap.DcmLdap.java

private static Hashtable<?, ?> ldapEnv(CommandLine cl) {
    Hashtable<String, Object> env = new Hashtable<>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put("java.naming.ldap.attributes.binary", "dicomVendorData");
    env.put(Context.PROVIDER_URL, cl.getOptionValue("H", DEFAULT_LDAP_URI));
    env.put(Context.SECURITY_PRINCIPAL, cl.getOptionValue("D", DEFAULT_BIND_DN));
    env.put(Context.SECURITY_CREDENTIALS, cl.getOptionValue("w", DEFAULT_PASSWORD));
    return env;//from   w  w w .  j a  v a2 s  . c  om
}

From source file:com.hs.mail.security.login.JndiLoginModule.java

@SuppressWarnings("unchecked")
protected DirContext open() throws NamingException {
    if (context == null) {
        try {//  w w  w.ja  v a  2 s.c o  m
            // Set up the environment for creating the initial context
            Hashtable env = new Hashtable();
            env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
            if (StringUtils.isNotEmpty(username)) {
                env.put(Context.SECURITY_PRINCIPAL, username);
            }
            if (StringUtils.isNotEmpty(password)) {
                env.put(Context.SECURITY_CREDENTIALS, password);
            }
            env.put(Context.PROVIDER_URL, url);
            env.put(Context.SECURITY_AUTHENTICATION, authentication);
            context = new InitialDirContext(env);
        } catch (NamingException e) {
            throw e;
        }
    }
    return context;
}