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.jboss.adminclient.connection.RemoteProfileServiceConnectionProvider.java

protected ProfileServiceConnectionImpl doConnect() {
    Properties env = new Properties();
    env.setProperty(Context.PROVIDER_URL, this.providerURL);
    ProfileService profileService;// www.  j  a  va 2s .c  o  m
    ManagementView managementView;
    DeploymentManager deploymentManager;
    ClassLoader originalContextClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
        if (this.principal != null) {
            env.setProperty(Context.INITIAL_CONTEXT_FACTORY, JNDI_LOGIN_INITIAL_CONTEXT_FACTORY);
            env.setProperty(Context.SECURITY_PRINCIPAL, this.principal);
            env.setProperty(Context.SECURITY_CREDENTIALS, this.credentials);
            log.debug("Connecting to Profile Service via remote JNDI using env [" + env + "]...");
            InitialContext initialContext = createInitialContext(env);
            profileService = (ProfileService) lookup(initialContext, SECURE_PROFILE_SERVICE_JNDI_NAME);
            managementView = (ManagementView) lookup(initialContext, SECURE_MANAGEMENT_VIEW_JNDI_NAME);
            deploymentManager = (DeploymentManager) lookup(initialContext, SECURE_DEPLOYMENT_MANAGER_JNDI_NAME);
        } else {
            env.setProperty(Context.INITIAL_CONTEXT_FACTORY, NAMING_CONTEXT_FACTORY);
            env.setProperty(JNP_DISABLE_DISCOVERY_JNP_INIT_PROP, "true");
            // Make sure the timeout always happens, even if the JBoss server is hung.
            env.setProperty("jnp.timeout", String.valueOf(JNP_TIMEOUT));
            env.setProperty("jnp.sotimeout", String.valueOf(JNP_SO_TIMEOUT));
            log.debug("Connecting to Profile Service via remote JNDI using env [" + env + "]...");
            InitialContext initialContext = createInitialContext(env);
            profileService = (ProfileService) lookup(initialContext, PROFILE_SERVICE_JNDI_NAME);
            managementView = profileService.getViewManager();
            deploymentManager = profileService.getDeploymentManager();
        }
    } finally {
        Thread.currentThread().setContextClassLoader(originalContextClassLoader);
    }
    return new ProfileServiceConnectionImpl(this, profileService, managementView, deploymentManager);
}

From source file:com.constellio.model.services.users.sync.FastBindConnectionControl.java

public boolean authenticate(String username, String password) {
    try {/*  w w w . ja  v  a 2 s .  co m*/
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, username);
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
        ctx.reconnect(connCtls);
        //         System.out.println(username + " is authenticated");
        return true;
    } catch (AuthenticationException e) {
        //         System.out.println(username + " is not authenticated");
        return false;
    } catch (NamingException e) {
        //         System.out.println(username + " is not authenticated");
        return false;
    }
}

From source file:org.apache.axis2.transport.amqp.common.AMQPConnectionFactoryManager.java

/**
 * Get the AMQP connection factory that matches the given properties, i.e. referring to
 * the same underlying connection factory. Used by the AMQPSender to determine if already
 * available resources should be used for outgoing messages
 *
 * @param props a Map of connection factory JNDI properties and name
 * @return the AMQP connection factory or null if no connection factory compatible
 *         with the given properties exists
 *//* w w  w .  j  a v a  2 s  .c o m*/
public AMQPConnectionFactory getAMQPConnectionFactory(Map<String, String> props) {
    for (AMQPConnectionFactory cf : connectionFactories.values()) {
        Map<String, String> cfProperties = cf.getParameters();

        if (equals(props.get(AMQPConstants.PARAM_AMQP_CONFAC),
                cfProperties.get(AMQPConstants.PARAM_AMQP_CONFAC))
                && equals(props.get(Context.PROVIDER_URL), cfProperties.get(Context.PROVIDER_URL))
                && equals(props.get(Context.SECURITY_PRINCIPAL), cfProperties.get(Context.SECURITY_PRINCIPAL))
                && equals(props.get(Context.SECURITY_CREDENTIALS),
                        cfProperties.get(Context.SECURITY_CREDENTIALS))) {
            return cf;
        }
    }
    return null;
}

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

/**
 * {@inheritDoc}//  w  w  w . j  a va 2s. c  om
 */
@Override
public void afterPropertiesSet() throws Exception {
    // handled as part of setter in default class
    if (this.poolSystemProperties != null) {
        for (final Entry<String, String> entry : this.poolSystemProperties.entrySet()) {
            System.setProperty(entry.getKey(), entry.getValue());
        }
    }

    // check anonymous bind
    final Map<String, String> config = new HashMap<>(this.authenticatedEnvironment.size());
    config.putAll(this.authenticatedEnvironment);
    config.remove(Context.SECURITY_PRINCIPAL);
    config.remove(Context.SECURITY_CREDENTIALS);

    if (this.isSSLSocketFactoryRequired(config)) {
        final KeyStore trustStore = this.initTrustStore();
        ThreadSafeSSLSocketFactory.initTrustedSSLSocketFactory(trustStore);
        config.put("java.naming.ldap.factory.socket", ThreadSafeSSLSocketFactory.class.getName());
    }

    try {
        new InitialDirContext(new Hashtable<>(config));
        LOGGER.warn("LDAP server supports anonymous bind {}", config.get(Context.PROVIDER_URL));
    } catch (javax.naming.AuthenticationException | AuthenticationNotSupportedException ax) {
        // NO-OP - expected
    } catch (final NamingException nx) {
        LOGGER.error("Unable to connect to LDAP Server; check LDAP configuration", nx);
        return;
    }

    // Simple DN and password
    config.put(Context.SECURITY_PRINCIPAL, "daftAsABrush");
    config.put(Context.SECURITY_CREDENTIALS, "daftAsABrush");

    try {
        new InitialDirContext(new Hashtable<>(config));
        throw new AuthenticationException("The ldap server at " + config.get(Context.PROVIDER_URL)
                + " falls back to use anonymous bind if invalid security credentials are presented. This is not supported.");
    } catch (javax.naming.AuthenticationException | AuthenticationNotSupportedException ax) {
        LOGGER.info("LDAP server does not fall back to anonymous bind for a string uid and password at {}",
                config.get(Context.PROVIDER_URL));
    } catch (final NamingException nx) {
        LOGGER.info("LDAP server does not support simple string user ids and invalid credentials at {}",
                config.get(Context.PROVIDER_URL));
    }

    // DN and password
    config.put(Context.SECURITY_PRINCIPAL, "cn=daftAsABrush,dc=woof");
    config.put(Context.SECURITY_CREDENTIALS, "daftAsABrush");
    try {
        new InitialDirContext(new Hashtable<>(config));
        throw new AuthenticationException("The ldap server at " + config.get(Context.PROVIDER_URL)
                + " falls back to use anonymous bind if invalid security credentials are presented. This is not supported.");
    } catch (javax.naming.AuthenticationException | AuthenticationNotSupportedException ax) {
        LOGGER.info("LDAP server does not fall back to anonymous bind for a simple dn and password at {}",
                config.get(Context.PROVIDER_URL));
    } catch (final NamingException nx) {
        LOGGER.info("LDAP server does not support simple DN and invalid credentials at {}",
                config.get(Context.PROVIDER_URL));
    }

    // Check more if we have a real principal we expect to work
    final String principal = this.defaultEnvironment.get(Context.SECURITY_PRINCIPAL);
    if (principal != null) {
        config.put(Context.SECURITY_PRINCIPAL, principal);
        config.put(Context.SECURITY_CREDENTIALS, "sdasdasdasdasd123123123");

        try {
            new InitialDirContext(new Hashtable<>(config));
            throw new AuthenticationException("The ldap server at " + config.get(Context.PROVIDER_URL)
                    + " falls back to use anonymous bind for a known principal if invalid security credentials are presented. This is not supported.");
        } catch (final javax.naming.AuthenticationException ax) {
            LOGGER.info(
                    "LDAP server does not fall back to anonymous bind for known principal and invalid password at {}",
                    config.get(Context.PROVIDER_URL));
        } catch (final AuthenticationNotSupportedException ax) {
            LOGGER.info("LDAP server does not support the required authentication mechanism");
        } catch (final NamingException nx) {
            // NO-OP - covered in previous checks
        }
    }
}

From source file:hsa.awp.common.naming.TestLdapDirectoryAdapter.java

/**
 * Adds expectations for context configuration to the adapter.
 *
 * @throws Exception if something went wrong.
 *//*  w  ww.j  av  a 2 s .c  o m*/
private void mockExpectConfiguration() throws Exception {

    mockery.checking(new Expectations() {
        {
            oneOf(directoryContext).addToEnvironment(Context.INITIAL_CONTEXT_FACTORY,
                    "com.sun.jndi.ldap.LdapCtxFactory");

            oneOf(directoryContext).addToEnvironment(Context.PROVIDER_URL,
                    ldapConfig.getProperty("naming.providerURL"));

            oneOf(directoryContext).addToEnvironment(Context.SECURITY_PRINCIPAL,
                    ldapConfig.getProperty("naming.securityPrincipal"));

            oneOf(directoryContext).addToEnvironment(Context.SECURITY_CREDENTIALS,
                    ldapConfig.getProperty("naming.securityCredentials"));

            oneOf(directoryContext).addToEnvironment(Context.SECURITY_PROTOCOL,
                    ldapConfig.getProperty("naming.securityProtocol"));

            oneOf(directoryContext).addToEnvironment(Context.SECURITY_AUTHENTICATION,
                    ldapConfig.getProperty("naming.securityAuthentication"));
        }
    });
}

From source file:org.apache.axis2.transport.jms.JMSConnectionFactoryManager.java

/**
 * Get the JMS connection factory that matches the given properties, i.e. referring to
 * the same underlying connection factory. Used by the JMSSender to determine if already
 * available resources should be used for outgoing messages
 *
 * @param props a Map of connection factory JNDI properties and name
 * @return the JMS connection factory or null if no connection factory compatible
 *         with the given properties exists
 *//*www . ja  v  a 2 s .com*/
public JMSConnectionFactory getJMSConnectionFactory(Map<String, String> props) {
    for (JMSConnectionFactory cf : connectionFactories.values()) {
        Map<String, String> cfProperties = cf.getParameters();

        if (equals(props.get(JMSConstants.PARAM_CONFAC_JNDI_NAME),
                cfProperties.get(JMSConstants.PARAM_CONFAC_JNDI_NAME))
                && equals(props.get(Context.INITIAL_CONTEXT_FACTORY),
                        cfProperties.get(Context.INITIAL_CONTEXT_FACTORY))
                && equals(props.get(Context.PROVIDER_URL), cfProperties.get(Context.PROVIDER_URL))
                && equals(props.get(Context.SECURITY_PRINCIPAL), cfProperties.get(Context.SECURITY_PRINCIPAL))
                && equals(props.get(Context.SECURITY_CREDENTIALS),
                        cfProperties.get(Context.SECURITY_CREDENTIALS))) {
            return cf;
        }
    }
    return null;
}

From source file:gda.jython.authenticator.LdapAuthenticator.java

private boolean checkAuthenticatedUsingServer(String ldapURL, String fedId, String password)
        throws NamingException {

    InitialLdapContext ctx = null;
    try {/*from  w  ww. j  av a  2 s  . c  o m*/
        Hashtable<String, String> env = new Hashtable<String, String>();
        String principal = "CN=" + fedId + adminName;
        env.put(Context.INITIAL_CONTEXT_FACTORY, ldapContext);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, principal);
        env.put(Context.SECURITY_CREDENTIALS, password);
        env.put(Context.PROVIDER_URL, ldapURL);
        ctx = new InitialLdapContext(env, null);
        //if no exception then password is OK
        return true;
    } catch (AuthenticationException ae) {
        logger.error("LDAP AuthenticationException: " + StringEscapeUtils.escapeJava(ae.getMessage()));
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
            }
        }
    }
    return false;
}

From source file:security.AuthenticationManager.java

private static Hashtable<String, String> buildEnvContext(String username, String password,
        String contextFactory, String ldapUrl, String principalDomain) {
    Hashtable<String, String> env = new Hashtable<>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
    env.put(Context.PROVIDER_URL, ldapUrl);
    env.put(Context.SECURITY_PRINCIPAL, username + principalDomain);
    env.put(Context.SECURITY_CREDENTIALS, password);
    return env;/*w  w w  .ja v  a2 s.c om*/
}

From source file:org.hyperic.hq.plugin.netservices.LDAPCollector.java

public void collect() {

    // Setup initial LDAP properties
    Properties env = new Properties();
    Properties props = getProperties();

    // 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");
    }//from   ww  w  . j  a  v  a2 s  .co  m

    // Set the LDAP url
    if (isSSL()) {
        env.put("java.naming.ldap.factory.socket", LDAPSSLSocketFactory.class.getName());
        env.put(Context.SECURITY_PROTOCOL, "ssl");
    }
    String providerUrl = "ldap://" + getHostname() + ":" + getPort();
    env.setProperty(Context.PROVIDER_URL, providerUrl);

    // For log track
    setSource(providerUrl);

    // Follow referrals automatically
    env.setProperty(Context.REFERRAL, "follow");

    // Base DN
    String baseDN = props.getProperty(PROP_BASEDN);
    if (baseDN == null) {
        setErrorMessage("No Base DN given, refusing login");
        setAvailability(false);
        return;
    }

    // Search filter
    String filter = props.getProperty(PROP_FILTER);

    // Load any information we may need to bind
    String bindDN = props.getProperty(PROP_BINDDN);
    String bindPW = props.getProperty(PROP_BINDPW);
    if (bindDN != null) {
        env.setProperty(Context.SECURITY_PRINCIPAL, bindDN);
        env.setProperty(Context.SECURITY_CREDENTIALS, bindPW);
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    }

    if (log.isDebugEnabled()) {
        log.debug("Using LDAP environment: " + env);
    }

    try {
        startTime();
        InitialLdapContext ctx = new InitialLdapContext(env, null);
        endTime();

        setAvailability(true);

        // If a search filter is specified, run the search and return the
        // number of matches as a metric
        if (filter != null) {
            log.debug("Using LDAP filter=" + filter);
            NamingEnumeration answer = ctx.search(baseDN, filter, getSearchControls());

            long matches = 0;
            while (answer.hasMore()) {
                matches++;
                answer.next();
            }

            setValue("NumberofMatches", matches);
        }
    } catch (Exception e) {
        setAvailability(false);
        if (log.isDebugEnabled()) {
            log.debug("LDAP check failed: " + e, e);
        }

        setErrorMessage("LDAP check failed: " + e);
    }
}

From source file:org.jamwiki.ldap.LdapUserHandler.java

/**
 * Connect to the LDAP server and return a context.
 *
 * @return The LDAP context to use when retrieving user information.
 *///w  ww  . jav  a 2  s  .c  o  m
private InitialDirContext getContext(String username, String password) throws Exception {
    // Set up the environment for creating the initial context
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, Environment.getValue(Environment.PROP_LDAP_FACTORY_CLASS));
    env.put(Context.PROVIDER_URL, Environment.getValue(Environment.PROP_LDAP_URL));
    if (!StringUtils.isBlank(username)) {
        // "simple" "DIGEST-MD5"
        env.put(Context.SECURITY_AUTHENTICATION,
                Environment.getValue(Environment.PROP_LDAP_SECURITY_AUTHENTICATION));
        // cn=login, ou=NewHires, o=JNDITutorial
        env.put(Context.SECURITY_PRINCIPAL, username);
        env.put(Context.SECURITY_CREDENTIALS, password);
    }
    InitialDirContext ctx = new InitialDirContext(env);
    return ctx;
}