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:net.identio.server.service.authentication.ldap.LdapConnectionFactory.java

private InitialLdapContext createContext(LdapAuthMethod ldapAuthMethod, String userDn, String password)
        throws NamingException {

    LOG.debug("Begin creation of an LDAP connection to: {}", ldapAuthMethod.getName());

    int currentUrlIndexTs = currentUrlIndex;

    String currentUrl = ldapAuthMethod.getLdapUrl().get(currentUrlIndexTs);

    Hashtable<String, String> env = new Hashtable<>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, currentUrl);

    if (currentUrl.startsWith("ldaps://")) {

        // Add a custom SSL Socket factory to validate server CA
        env.put("java.naming.ldap.factory.socket",
                "net.identio.server.service.authentication.ldap.LdapSslSocketFactory");
    }/*from ww w  .j a  va 2 s. c o  m*/

    if (userDn != null) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, userDn);
        env.put(Context.SECURITY_CREDENTIALS, password);
    }

    InitialLdapContext ctx;

    try {
        ctx = new InitialLdapContext(env, null);
    } catch (CommunicationException e) {

        LOG.error("Error when contacting LDAP server {}", ldapAuthMethod.getLdapUrl().get(currentUrlIndexTs));

        if (ldapAuthMethod.getLdapUrl().size() > 1) {
            int newCurrentUrlIndex = currentUrlIndexTs < ldapAuthMethod.getLdapUrl().size() - 1
                    ? currentUrlIndexTs + 1
                    : 0;

            LOG.error("Switching to LDAP server {}", ldapAuthMethod.getLdapUrl().get(newCurrentUrlIndex));

            currentUrlIndex = newCurrentUrlIndex;

            env.put(Context.PROVIDER_URL, ldapAuthMethod.getLdapUrl().get(newCurrentUrlIndex));

            ctx = new InitialLdapContext(env, null);
        } else {
            throw e;
        }
    }

    return ctx;
}

From source file:org.hyperic.hq.plugin.tomcat.JBossUtil.java

public static MBeanServerConnection getMBeanServerConnection(Properties config)
        throws NamingException, RemoteException {
    MBeanServerConnection adaptor;

    Properties props = new Properties();

    for (int i = 0; i < NAMING_PROPS.length; i++) {
        props.setProperty(NAMING_PROPS[i][0], NAMING_PROPS[i][1]);
    }//from w w w  . j  a v  a2 s  .c  o  m

    props.putAll(config);
    props.put("java.naming.provider.url", config.get("jmx.url"));

    if (props.getProperty(Context.SECURITY_PRINCIPAL) != null) {
        props.setProperty(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
    }

    InitialContext ctx = new InitialContext(props);

    try {
        Object o = ctx.lookup(props.getProperty(PROP_NAMING_CONNECTOR));
        log.debug("=> " + Arrays.asList(o.getClass().getInterfaces()));
        adaptor = (MBeanServerConnection) o;
    } finally {
        ctx.close();
    }

    return adaptor;
}

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

License:asdf

@Test
public void testAuthWithNoCredsStrong() throws Exception {
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.SECURITY_PRINCIPAL, "");
    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(props.getCredentials() == null);
}

From source file:com.dianping.cat.system.page.login.service.SessionManager.java

public SessionManager() {
    super();/*w w  w  .j a v a2 s  . c  om*/
    AuthType type = AuthType.valueOf(CatPropertyProvider.INST.getProperty("CAT_AUTH_TYPE", "ADMIN_PWD"));
    switch (type) {
    case NOP:
        tokenCreator = new Function<Credential, Token>() {
            @Override
            public Token apply(Credential credential) {
                String account = credential.getAccount();
                return new Token(account, account);
            }
        };
        break;
    case LDAP:
        final String ldapUrl = CatPropertyProvider.INST.getProperty("CAT_LDAP_URL", null);
        if (StringUtils.isBlank(ldapUrl)) {
            throw new IllegalArgumentException("required CAT_LDAP_URL");
        }
        final String userDnTpl = CatPropertyProvider.INST.getProperty("CAT_LDAP_USER_DN_TPL", null);
        if (StringUtils.isBlank(userDnTpl)) {
            throw new IllegalArgumentException("required CAT_LDAP_USER_DN_TPL");
        }
        final String userDisplayAttr = CatPropertyProvider.INST.getProperty("CAT_LDAP_USER_DISPLAY_ATTR", null);
        final Pattern pattern = Pattern.compile("\\{0}");
        final Matcher userDnTplMatcher = pattern.matcher(userDnTpl);
        final String[] attrs = userDisplayAttr == null ? null : new String[] { userDisplayAttr };
        tokenCreator = new Function<Credential, Token>() {
            @Override
            public Token apply(Credential credential) {
                final String account = credential.getAccount();
                final String pwd = credential.getPassword();
                if (StringUtils.isEmpty(account) || StringUtils.isEmpty(pwd)) {
                    return null;
                }
                Hashtable<String, String> env = new Hashtable<String, String>();
                env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
                env.put(Context.PROVIDER_URL, ldapUrl);// LDAP server
                String userDn = userDnTplMatcher.replaceAll(account);
                env.put(Context.SECURITY_PRINCIPAL, pwd);
                env.put(Context.SECURITY_CREDENTIALS, pwd);
                try {
                    InitialLdapContext context = new InitialLdapContext(env, null);
                    final String baseDn = context.getNameInNamespace();
                    if (userDn.endsWith(baseDn)) {
                        userDn = userDn.substring(0, userDn.length() - baseDn.length() - 1);
                    }
                    String displayName = null;
                    if (attrs != null) {
                        final Attributes attributes = context.getAttributes(userDn, attrs);
                        if (attributes.size() > 0) {
                            displayName = attributes.getAll().next().get().toString();
                        }
                    }

                    return new Token(account, displayName == null ? account : displayName);
                } catch (Exception e) {
                    Cat.logError(e);
                    return null;
                }
            }

        };
        break;
    case ADMIN_PWD:
        final String p = CatPropertyProvider.INST.getProperty("CAT_ADMIN_PWD", "admin");

        tokenCreator = new Function<Credential, Token>() {
            @Override
            public Token apply(Credential credential) {
                String account = credential.getAccount();

                if ("admin".equals(account) && p.equals(credential.getPassword())) {
                    return new Token(account, account);
                }
                return null;
            }

        };
        break;
    }
}

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;//from w ww  .  ja va 2 s  .  c  om
    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: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
 *//* www. j  av  a 2  s  . c om*/
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:com.constellio.model.services.users.sync.FastBindConnectionControl.java

public boolean authenticate(String username, String password) {
    try {//  w ww  . j  av  a  2s. c  om
        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:hsa.awp.common.naming.TestLdapDirectoryAdapter.java

/**
 * Adds expectations for context configuration to the adapter.
 *
 * @throws Exception if something went wrong.
 *//*from  w w  w  .  j  a  va2  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
 *//*w w  w.  j a v  a 2s.c  om*/
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:de.acosix.alfresco.mtsupport.repo.auth.ldap.LDAPInitialDirContextFactoryImpl.java

/**
 * {@inheritDoc}//from   ww w  .j  a  va 2 s.  co m
 */
@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
        }
    }
}