Example usage for javax.naming Context SECURITY_PRINCIPAL

List of usage examples for javax.naming Context SECURITY_PRINCIPAL

Introduction

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

Prototype

String SECURITY_PRINCIPAL

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

Click Source Link

Document

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

Usage

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 a v  a 2  s . co  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;/*from w w  w  . j a  v  a 2 s .  co m*/
}

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 w  w w  .  j  a v  a 2  s.  com

    // 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.
 *//*from   ww  w .  j a v  a 2s.co 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;
}

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

private static ConnectionFactory lookupConnectionFactoryWithJndi(JmsConnectorProperties connectorProperties)
        throws Exception {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.PROVIDER_URL, connectorProperties.getJndiProviderUrl());
    env.put(Context.INITIAL_CONTEXT_FACTORY, connectorProperties.getJndiInitialContextFactory());
    env.put(Context.SECURITY_PRINCIPAL, connectorProperties.getUsername());
    env.put(Context.SECURITY_CREDENTIALS, connectorProperties.getPassword());

    initialContext = new InitialContext(env);
    String connectionFactoryName = connectorProperties.getJndiConnectionFactoryName();
    return (ConnectionFactory) initialContext.lookup(connectionFactoryName);
}

From source file:org.apache.directory.server.core.jndi.LdapJndiPropertiesTest.java

License:asdf

@Test
public void testAuthWithCredsStrong() throws Exception {
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.SECURITY_PRINCIPAL, "");
    env.put(Context.SECURITY_CREDENTIALS, "asdf");
    env.put(Context.SECURITY_AUTHENTICATION, "DIGEST-MD5 CRAM-MD5");
    env.put(Context.PROVIDER_URL, "");
    LdapJndiProperties props = LdapJndiProperties.getLdapJndiProperties(env);
    assertEquals(AuthenticationLevel.STRONG, props.getAuthenticationLevel());
    assertTrue(ArrayUtils.isEquals(Strings.getBytesUtf8("asdf"), props.getCredentials()));
}

From source file:org.exist.security.realm.ldap.LdapContextFactory.java

public LdapContext getLdapContext(String username, final String password,
        final Map<String, Object> additionalEnv) throws NamingException {

    if (url == null) {
        throw new IllegalStateException("An LDAP URL must be specified of the form ldap://<hostname>:<port>");
    }//from  www  .  j av a2  s  .c  o  m

    if (StringUtils.isBlank(password)) {
        throw new IllegalStateException("Password for LDAP authentication may not be empty.");
    }

    if (username != null && principalPattern != null) {
        username = principalPatternFormat.format(new String[] { username });
    }

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

    env.put(Context.SECURITY_AUTHENTICATION, authentication);
    if (ssl) {
        env.put(Context.SECURITY_PROTOCOL, "ssl");
    }

    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);

    //Absolutely nessecary for working with Active Directory
    env.put("java.naming.ldap.attributes.binary", "objectSid");

    // the following is helpful in debugging errors
    //env.put("com.sun.jndi.ldap.trace.ber", System.err);

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

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

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

    return new InitialLdapContext(env, null);
}

From source file:org.apache.synapse.message.store.impl.jdbc.util.JDBCConfiguration.java

/**
 * Reading lookup information for existing datasource
 *
 * @param parameters -  parameters given in configuration
 *///  ww  w  . jav a  2s .c  o m
private void readLookupConfig(Map<String, Object> parameters) {
    String dataSourceName = (String) parameters.get(JDBCMessageStoreConstants.JDBC_DSNAME);
    this.setDataSourceName(dataSourceName);

    if (parameters.get(JDBCMessageStoreConstants.JDBC_ICCLASS) != null) {
        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, parameters.get(JDBCMessageStoreConstants.JDBC_ICCLASS));
        props.put(Context.PROVIDER_URL, parameters.get(JDBCMessageStoreConstants.JDBC_CONNECTION_URL));
        props.put(Context.SECURITY_PRINCIPAL, parameters.get(JDBCMessageStoreConstants.JDBC_USERNAME));
        props.put(Context.SECURITY_CREDENTIALS, parameters.get(JDBCMessageStoreConstants.JDBC_PASSWORD));

        this.setJndiProperties(props);
    }
}

From source file:org.apache.lens.server.user.LDAPBackedDatabaseUserConfigLoader.java

/**
 * Instantiates a new LDAP backed database user config loader.
 *
 * @param conf the conf/*from  w ww .  ja  v a 2 s  .c  o  m*/
 * @throws UserConfigLoaderException the user config loader exception
 */
public LDAPBackedDatabaseUserConfigLoader(final HiveConf conf) throws UserConfigLoaderException {
    super(conf);
    expiryHours = conf.getInt(LensConfConstants.USER_RESOLVER_CACHE_EXPIRY, 2);
    intermediateQuerySql = conf.get(LensConfConstants.USER_RESOLVER_LDAP_INTERMEDIATE_DB_QUERY);
    intermediateDeleteSql = conf.get(LensConfConstants.USER_RESOLVER_LDAP_INTERMEDIATE_DB_DELETE_SQL);
    intermediateInsertSql = conf.get(LensConfConstants.USER_RESOLVER_LDAP_INTERMEDIATE_DB_INSERT_SQL);
    ldapFields = conf.get(LensConfConstants.USER_RESOLVER_LDAP_FIELDS).split("\\s*,\\s*");
    searchBase = conf.get(LensConfConstants.USER_RESOLVER_LDAP_SEARCH_BASE);
    searchFilterPattern = conf.get(LensConfConstants.USER_RESOLVER_LDAP_SEARCH_FILTER);
    intermediateCache = CacheBuilder.newBuilder().expireAfterWrite(expiryHours, TimeUnit.HOURS)
            .maximumSize(conf.getInt(LensConfConstants.USER_RESOLVER_CACHE_MAX_SIZE, 100)).build();
    cache = CacheBuilder.newBuilder().expireAfterWrite(expiryHours, TimeUnit.HOURS)
            .maximumSize(conf.getInt(LensConfConstants.USER_RESOLVER_CACHE_MAX_SIZE, 100)).build();

    env = new Hashtable<String, Object>() {
        {
            put(Context.SECURITY_AUTHENTICATION, "simple");
            put(Context.SECURITY_PRINCIPAL, conf.get(LensConfConstants.USER_RESOLVER_LDAP_BIND_DN));
            put(Context.SECURITY_CREDENTIALS, conf.get(LensConfConstants.USER_RESOLVER_LDAP_BIND_PASSWORD));
            put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            put(Context.PROVIDER_URL, conf.get(LensConfConstants.USER_RESOLVER_LDAP_URL));
            put("java.naming.ldap.attributes.binary", "objectSID");
        }
    };
}

From source file:org.easy.ldap.LdapContextFactory.java

public DirContext createSecureContext(LdapName rootDn, LdapName principal, String password,
        String securityMethod) throws NamingException {
    Hashtable<String, String> environment = getEnviroment();
    environment.put(Context.PROVIDER_URL, createProviderUrl(rootDn.toString()));

    environment.put(Context.SECURITY_AUTHENTICATION, securityMethod);
    environment.put(Context.SECURITY_PRINCIPAL, principal.toString());
    environment.put(Context.SECURITY_CREDENTIALS, password);

    return createContext(environment);
}