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:com.zabbix.gateway.JMXItemChecker.java

public JMXItemChecker(JSONObject request) throws ZabbixException {
    super(request);

    try {//  ww  w.j a  v a 2  s. c o  m
        String conn = request.getString(JSON_TAG_CONN);
        int port = request.getInt(JSON_TAG_PORT);

        jmxc = null;
        mbsc = null;
        String jmx_url = "service:jmx:rmi:///jndi/rmi://[" + conn + "]:" + port + "/jmxrmi"; // default
        String jboss_url = "service:jmx:remoting-jmx://" + conn + ":" + port; // jboss
        String t3_url = "service:jmx:t3://" + conn + ":" + port
                + "/jndi/weblogic.management.mbeanservers.runtime"; // T3
        String t3s_url = "service:jmx:t3s://" + conn + ":" + port
                + "/jndi/weblogic.management.mbeanservers.runtime"; // T3S
        protocol = "jmx";
        String tested_url = jmx_url;

        username = request.optString(JSON_TAG_USERNAME, null);
        password = request.optString(JSON_TAG_PASSWORD, null);

        //if (null != username && null == password || null == username && null != password)
        //   throw new IllegalArgumentException("invalid username and password nullness combination");

        if (null != username) {
            // Testing if username is like "<user>:<protocol>"
            int protocol_in_username = username.indexOf(':');
            if (protocol_in_username != -1) {
                String result[] = username.split(":");
                username = result[0];
                protocol = result[1];
            }
        }

        switch (protocol) {
        case "jmx":
        case "jmxs":
            tested_url = jmx_url;
            break;
        case "jboss":
            tested_url = jboss_url;
            break;
        case "t3":
            tested_url = t3_url;
            break;
        case "t3s":
            tested_url = t3s_url;
            break;
        default:
            tested_url = jmx_url;
            break;
        }

        logger.info("Using url '{}' with user '{}'", tested_url, username);

        HashMap<String, Object> env = new HashMap<String, Object>();
        env.put(JMXConnector.CREDENTIALS, new String[] { username, password });

        if (protocol.equals("t3") || protocol.equals("t3s")) {
            env.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote");
            env.put(javax.naming.Context.SECURITY_PRINCIPAL, ((String[]) env.get(JMXConnector.CREDENTIALS))[0]);
            env.put(javax.naming.Context.SECURITY_CREDENTIALS,
                    ((String[]) env.get(JMXConnector.CREDENTIALS))[1]);
        }

        // Required by SSL
        if (protocol.equals("jmxs")) {
            env.put("com.sun.jndi.rmi.factory.socket", new SslRMIClientSocketFactory());
        }

        url = new JMXServiceURL(tested_url);
        jmxc = ZabbixJMXConnectorFactory.connect(url, env);
        mbsc = jmxc.getMBeanServerConnection();
    } catch (Exception e) {
        throw new ZabbixException(e);
    } finally {
        try {
            if (null != jmxc)
                jmxc.close();
        } catch (java.io.IOException exception) {
        }

        jmxc = null;
        mbsc = null;
    }
}

From source file:org.jboss.test.security.test.SubjectContextUnitTestCase.java

public void testAllAuthMethod() throws Exception {
    log.debug("+++ testAllAuthMethod()");
    Properties env = new Properties();
    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.security.jndi.JndiLoginInitialContextFactory");
    env.setProperty(Context.SECURITY_PRINCIPAL, "jduke");
    env.setProperty(Context.SECURITY_CREDENTIALS, "theduke");
    InitialContext ctx = new InitialContext(env);
    Object obj = ctx.lookup("jacc/Secured");
    obj = PortableRemoteObject.narrow(obj, SecuredServiceRemoteHome.class);
    SecuredServiceRemoteHome home = (SecuredServiceRemoteHome) obj;
    log.debug("Found SecuredServiceRemoteHome");
    SecuredServiceRemote bean = home.create();
    log.debug("Created SecuredServiceRemote");

    Principal callerIdentity = new SimplePrincipal("jduke");
    Principal runAsIdentity = new SimplePrincipal("runAsUser");
    HashSet expectedCallerRoles = new HashSet();
    expectedCallerRoles.add("groupMemberCaller");
    expectedCallerRoles.add("userCaller");
    expectedCallerRoles.add("allAuthCaller");
    expectedCallerRoles.add("webUser");
    HashSet expectedRunAsRoles = new HashSet();
    expectedRunAsRoles.add("identitySubstitutionCaller");
    expectedRunAsRoles.add("extraRunAsRole");
    CallerInfo info = new CallerInfo(callerIdentity, runAsIdentity, expectedCallerRoles, expectedRunAsRoles);
    bean.allAuthMethod(info);//  ww w .j  a v a  2  s.c  o m
    bean.remove();
}

From source file:org.apache.cloudstack.ldap.LdapContextFactory.java

private Hashtable<String, String> getEnvironment(final String principal, final String password,
        final String providerUrl, final boolean isSystemContext, Long domainId) {
    final String factory = _ldapConfiguration.getFactory();
    String url = providerUrl == null ? _ldapConfiguration.getProviderUrl(domainId) : providerUrl;
    if (StringUtils.isEmpty(url) && domainId != null) {
        //try a default ldap implementation
        url = _ldapConfiguration.getProviderUrl(null);
    }//from w ww  .j  av  a  2 s  .c o  m

    final Hashtable<String, String> environment = new Hashtable<>();

    environment.put(Context.INITIAL_CONTEXT_FACTORY, factory);
    environment.put(Context.PROVIDER_URL, url);
    environment.put("com.sun.jndi.ldap.read.timeout", _ldapConfiguration.getReadTimeout(domainId).toString());
    environment.put("com.sun.jndi.ldap.connect.pool", "true");

    enableSSL(environment);
    setAuthentication(environment, isSystemContext, domainId);

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

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

    return environment;
}

From source file:org.openiam.idm.srvc.synch.service.generic.LdapAdapterForGenericObject.java

private boolean connect(SynchConfig config) throws NamingException {

    Hashtable<String, String> envDC = new Hashtable();
    System.setProperty("javax.net.ssl.trustStore", keystore);

    String hostUrl = config.getSrcHost(); // managedSys.getHostUrl();
    log.debug("Directory host url:" + hostUrl);

    envDC.put(Context.PROVIDER_URL, hostUrl);
    envDC.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    envDC.put(Context.SECURITY_AUTHENTICATION, "simple"); // simple
    envDC.put(Context.SECURITY_PRINCIPAL, config.getSrcLoginId()); // "administrator@diamelle.local"
    envDC.put(Context.SECURITY_CREDENTIALS, config.getSrcPassword());

    if (hostUrl.contains("ldaps")) {

        envDC.put(Context.SECURITY_PROTOCOL, "SSL");
    }//from  w w  w . j  a  va 2s  .  co m

    ctx = new InitialLdapContext(envDC, null);
    if (ctx != null) {
        return true;
    }

    return false;

}

From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java

public boolean authenticateUser(String userLogin, UserEdit edit, String password) {
    Hashtable env = new Hashtable();
    InitialDirContext ctx;/* ww  w  . ja  va  2 s.c  o  m*/

    String INIT_CTX = "com.sun.jndi.ldap.LdapCtxFactory";
    String MY_HOST = getLdapHost() + ":" + getLdapPort();
    String cn;
    boolean returnVal = false;

    if (!password.equals("")) {

        env.put(Context.INITIAL_CONTEXT_FACTORY, INIT_CTX);
        env.put(Context.PROVIDER_URL, MY_HOST);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_CREDENTIALS, "secret");

        String[] returnAttribute = { "ou" };
        SearchControls srchControls = new SearchControls();
        srchControls.setReturningAttributes(returnAttribute);
        srchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String searchFilter = "(&(objectclass=person)(uid=" + escapeSearchFilterTerm(userLogin) + "))";

        try {
            ctx = new InitialDirContext(env);
            NamingEnumeration answer = ctx.search(getBasePath(), searchFilter, srchControls);
            String trobat = "false";

            while (answer.hasMore() && trobat.equals("false")) {

                SearchResult sr = (SearchResult) answer.next();
                String dn = sr.getName().toString() + "," + getBasePath();

                // Second binding
                Hashtable authEnv = new Hashtable();
                try {
                    authEnv.put(Context.INITIAL_CONTEXT_FACTORY, INIT_CTX);
                    authEnv.put(Context.PROVIDER_URL, MY_HOST);
                    authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
                    authEnv.put(Context.SECURITY_PRINCIPAL, sr.getName() + "," + getBasePath());
                    authEnv.put(Context.SECURITY_CREDENTIALS, password);
                    try {
                        DirContext authContext = new InitialDirContext(authEnv);
                        returnVal = true;
                        trobat = "true";
                        authContext.close();
                    } catch (AuthenticationException ae) {
                        M_log.info("Access forbidden");
                    }

                } catch (NamingException namEx) {
                    M_log.info("User doesn't exist");
                    returnVal = false;
                    namEx.printStackTrace();
                }
            }
            if (trobat.equals("false"))
                returnVal = false;

        } catch (NamingException namEx) {
            namEx.printStackTrace();
            returnVal = false;
        }
    }
    return returnVal;
}

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);
    }//from w w  w  .ja va 2  s.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  w w. j a v  a  2 s .c  om
 * @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");
    }/*from   w w  w  .  j ava 2 s.c  o  m*/
    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 {//  w  w w .  j  a v  a 2  s  .  c  o m
        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);
    }
}