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:iplatform.admin.ui.server.auth.ad.ActiveDirectoryLdapAuthenticationProvider.java

private DirContext bindAsUser(String username, String password) {
    // TODO. add DNS lookup based on domain
    final String bindUrl = url;

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    String bindPrincipal = createBindPrincipal(username);
    env.put(Context.SECURITY_PRINCIPAL, bindPrincipal);
    env.put(Context.PROVIDER_URL, bindUrl);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.OBJECT_FACTORIES, DefaultDirObjectFactory.class.getName());

    try {//from w  w w . j  ava  2s .  c  om
        return contextFactory.createContext(env);
    } catch (NamingException e) {
        if ((e instanceof AuthenticationException) || (e instanceof OperationNotSupportedException)) {
            handleBindException(bindPrincipal, e);
            throw badCredentials(e);
        } else {
            throw LdapUtils.convertLdapException(e);
        }
    }
}

From source file:py.una.pol.karaku.security.KarakuUserService.java

private InitialDirContext getInitialDirContext(String user, String pass) throws NamingException {

    Map<Object, String> env = new HashMap<Object, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, getServerLocation());

    env.put(Context.SECURITY_PRINCIPAL, user);
    env.put(Context.SECURITY_CREDENTIALS, pass);
    return new InitialDirContext(new Hashtable<Object, String>(env));
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPDirectory.java

/**
 * @return connection parameters to use for all LDAP queries
 *//*from ww w . j  av  a  2  s .c  o  m*/
protected Properties computeContextProperties() throws DirectoryException {
    LDAPDirectoryDescriptor ldapDirectoryDesc = getDescriptor();
    // Initialization of LDAP connection parameters from parameters
    // registered in the LDAP "server" extension point
    Properties props = new Properties();
    LDAPServerDescriptor serverConfig = getServer();

    if (null == serverConfig) {
        throw new DirectoryException(
                "LDAP server configuration not found: " + ldapDirectoryDesc.getServerName());
    }

    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    /*
     * Get initial connection URLs, dynamic URLs may cause the list to be updated when creating the session
     */
    String ldapUrls = serverConfig.getLdapUrls();
    if (ldapUrls == null) {
        throw new DirectoryException("Server LDAP URL configuration is missing for directory " + getName());
    }
    props.put(Context.PROVIDER_URL, ldapUrls);

    // define how referrals are handled
    if (!getDescriptor().getFollowReferrals()) {
        props.put(Context.REFERRAL, "ignore");
    } else {
        // this is the default mode
        props.put(Context.REFERRAL, "follow");
    }

    /*
     * SSL Connections do not work with connection timeout property
     */
    if (serverConfig.getConnectionTimeout() > -1) {
        if (!serverConfig.useSsl()) {
            props.put("com.sun.jndi.ldap.connect.timeout",
                    Integer.toString(serverConfig.getConnectionTimeout()));
        } else {
            log.warn("SSL connections do not operate correctly"
                    + " when used with the connection timeout parameter, disabling timout");
        }
    }

    String bindDn = serverConfig.getBindDn();
    if (bindDn != null) {
        // Authenticated connection
        props.put(Context.SECURITY_PRINCIPAL, bindDn);
        props.put(Context.SECURITY_CREDENTIALS, serverConfig.getBindPassword());
    }

    if (serverConfig.isPoolingEnabled()) {
        // Enable connection pooling
        props.put("com.sun.jndi.ldap.connect.pool", "true");
        props.put("com.sun.jndi.ldap.connect.pool.protocol", "plain ssl");
        props.put("com.sun.jndi.ldap.connect.pool.authentication", "none simple DIGEST-MD5");
        props.put("com.sun.jndi.ldap.connect.pool.timeout", "1800000"); // 30
        // min
    }

    if (!serverConfig.isVerifyServerCert() && serverConfig.useSsl) {
        props.put("java.naming.ldap.factory.socket",
                "org.nuxeo.ecm.directory.ldap.LDAPDirectory$TrustingSSLSocketFactory");
    }

    return props;
}

From source file:org.sonar.plugins.ldap.LdapContextFactory.java

private Properties getEnvironment(@Nullable String principal, @Nullable String credentials, boolean pooling) {
    Properties env = new Properties();
    env.put(Context.SECURITY_AUTHENTICATION, authentication);
    if (realm != null) {
        env.put(SASL_REALM_PROPERTY, realm);
    }//from w ww .  j  a  v  a  2 s.c om
    if (pooling) {
        // Enable connection pooling
        env.put(SUN_CONNECTION_POOLING_PROPERTY, "true");
    }
    env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
    env.put(Context.PROVIDER_URL, providerUrl);
    env.put(Context.REFERRAL, DEFAULT_REFERRAL);
    if (principal != null) {
        env.put(Context.SECURITY_PRINCIPAL, principal);
    }
    // Note: debug is intentionally was placed here - in order to not expose password in log
    LOG.debug("Initializing LDAP context {}", env);
    if (credentials != null) {
        env.put(Context.SECURITY_CREDENTIALS, credentials);
    }
    return env;
}

From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java

private void createLdapContext() throws Throwable {
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapUrl);
    if (ldapUrl.startsWith("ldaps")
            && (config.getSSLTrustStorePath() != null && !config.getSSLTrustStorePath().trim().isEmpty())) {
        env.put("java.naming.ldap.factory.socket",
                "org.apache.ranger.ldapusersync.process.CustomSSLSocketFactory");
    }//from   ww w.jav  a 2 s. co  m

    ldapContext = new InitialLdapContext(env, null);
    if (!ldapUrl.startsWith("ldaps")) {
        if (config.isStartTlsEnabled()) {
            tls = (StartTlsResponse) ldapContext.extendedOperation(new StartTlsRequest());
            if (config.getSSLTrustStorePath() != null && !config.getSSLTrustStorePath().trim().isEmpty()) {
                tls.negotiate(CustomSSLSocketFactory.getDefault());
            } else {
                tls.negotiate();
            }
            LOG.info("Starting TLS session...");
        }
    }

    ldapContext.addToEnvironment(Context.SECURITY_PRINCIPAL, ldapBindDn);
    ldapContext.addToEnvironment(Context.SECURITY_CREDENTIALS, ldapBindPassword);
    ldapContext.addToEnvironment(Context.SECURITY_AUTHENTICATION, ldapAuthenticationMechanism);
    ldapContext.addToEnvironment(Context.REFERRAL, ldapReferral);
}

From source file:org.jsecurity.realm.ldap.DefaultLdapContextFactory.java

public LdapContext getLdapContext(String username, String password) throws NamingException {
    if (searchBase == null) {
        throw new IllegalStateException("A search base must be specified.");
    }/* w w  w.  j  av a  2 s  .  c o m*/
    if (url == null) {
        throw new IllegalStateException("An LDAP URL must be specified of the form ldap://<hostname>:<port>");
    }

    if (username != null && principalSuffix != null) {
        username += principalSuffix;
    }

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

    env.put(Context.SECURITY_AUTHENTICATION, authentication);
    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);
    env.put(Context.REFERRAL, referral);

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

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

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

    return new InitialLdapContext(env, null);
}

From source file:org.olat.ldap.manager.LDAPLoginManagerImpl.java

/**
 * Connect to the LDAP server with System DN and Password
 * /*  w  ww .  ja va  2  s  . c  o  m*/
 * Configuration: LDAP URL = ldapContext.xml (property=ldapURL) System DN =
 * ldapContext.xml (property=ldapSystemDN) System PW = ldapContext.xml
 * (property=ldapSystemPW)
 * 
 * @return The LDAP connection (LdapContext) or NULL if connect fails
 * 
 * @throws NamingException
 */
public LdapContext bindSystem() {
    // set LDAP connection attributes
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapLoginModule.getLdapUrl());
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, ldapLoginModule.getLdapSystemDN());
    env.put(Context.SECURITY_CREDENTIALS, ldapLoginModule.getLdapSystemPW());
    if (ldapLoginModule.getLdapConnectionTimeout() != null) {
        env.put(TIMEOUT_KEY, ldapLoginModule.getLdapConnectionTimeout().toString());
    }

    // check ssl
    if (ldapLoginModule.isSslEnabled()) {
        enableSSL(env);
    }

    try {
        InitialLdapContext ctx = new InitialLdapContext(env, new Control[] {});
        ctx.getConnectControls();
        return ctx;
    } catch (NamingException e) {
        log.error("NamingException when trying to bind system with DN::" + ldapLoginModule.getLdapSystemDN()
                + " and PW::" + ldapLoginModule.getLdapSystemPW() + " on URL::" + ldapLoginModule.getLdapUrl(),
                e);
        return null;
    } catch (Exception e) {
        log.error("Exception when trying to bind system with DN::" + ldapLoginModule.getLdapSystemDN()
                + " and PW::" + ldapLoginModule.getLdapSystemPW() + " on URL::" + ldapLoginModule.getLdapUrl(),
                e);
        return null;
    }

}

From source file:org.jboss.additional.testsuite.jdkall.present.elytron.sasl.OtpSaslTestCase.java

/**
 * Check correct user attribute values in the LDAP when using OTP algorithm.
 *//*from   w  ww  .  java2 s  .co  m*/
private void assertSequenceAndHash(Integer expectedSequence, byte[] expectedHash) throws NamingException {
    final Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, LDAP_URL);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    env.put(Context.SECURITY_CREDENTIALS, "secret");
    final LdapContext ctx = new InitialLdapContext(env, null);
    NamingEnumeration<?> namingEnum = ctx.search("dc=wildfly,dc=org", new BasicAttributes("cn", "jduke"));
    if (namingEnum.hasMore()) {
        SearchResult sr = (SearchResult) namingEnum.next();
        Attributes attrs = sr.getAttributes();
        assertEquals("Unexpected sequence number in LDAP attribute", expectedSequence,
                new Integer(attrs.get("telephoneNumber").get().toString()));
        assertEquals("Unexpected hash value in LDAP attribute",
                Base64.getEncoder().encodeToString(expectedHash), attrs.get("title").get().toString());
    } else {
        fail("User not found in LDAP");
    }

    namingEnum.close();
    ctx.close();
}

From source file:it.webappcommon.lib.LDAPHelper.java

/**
 * @param args/*from  w  w w.ja  va 2  s .c o  m*/
 *            the command line arguments
 */
// public static void main(String[] args) {
private List<UserInfo> search(String filter) throws NamingException {
    DirContext ctx = null;
    SearchControls ctls = null;
    Properties env = new Properties();
    List<UserInfo> res = new ArrayList<UserInfo>();
    boolean trovatiRisultati = false;

    env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT);

    env.put(Context.PROVIDER_URL, "ldap://" + server + ":" + port);

    env.put(Context.SECURITY_AUTHENTICATION, "simple");

    if (org.apache.commons.lang3.StringUtils.isEmpty(loginDomain)) {
        env.put(Context.SECURITY_PRINCIPAL, loginUserName);
    } else {
        env.put(Context.SECURITY_PRINCIPAL, loginDomain + "\\" + loginUserName);
    }
    env.put(Context.SECURITY_CREDENTIALS, loginPassword);

    try {
        ctx = new InitialDirContext(env);

        ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // String filter = "";
        // // filter = "(&(objectClass=inetOrgPerson)(objectClass=person))";
        // filter = FILTER_USERS_ACTIVE;

        // Tutti i membri di un gruppo
        // (objectCategory=user)(memberOf=CN=QA Users,OU=Help
        // Desk,DC=dpetri,DC=net)

        // ESEMPI
        // http://www.petri.co.il/ldap_search_samples_for_windows_2003_and_exchange.htm

        // Account disabled
        // (UserAccountControl:1.2.840.113556.1.4.803:=2)

        NamingEnumeration<SearchResult> answer = ctx.search(areaWhereSearch, filter, ctls);

        UserInfo userInfo = null;
        while (answer.hasMoreElements()) {
            trovatiRisultati = true;

            SearchResult a = answer.nextElement();
            // logger.debug(a.getNameInNamespace());

            Attributes result = a.getAttributes();

            if (result == null) {
                // System.out.print("Attributi non presenti");
            } else {
                NamingEnumeration<? extends Attribute> attributi = result.getAll();

                userInfo = new UserInfo();
                while (attributi.hasMoreElements()) {
                    Attribute att = attributi.nextElement();
                    // logger.debug(att.getID());

                    String value = "";
                    // for (NamingEnumeration vals = att.getAll();
                    // vals.hasMoreElements(); logger.debug("\t" +
                    // vals.nextElement()))
                    // ;
                    NamingEnumeration<?> vals = att.getAll();
                    while (vals.hasMoreElements()) {
                        Object val = vals.nextElement();

                        // logger.debug("\t" + val);
                        value = (value.isEmpty()) ? value + val.toString() : value + ";" + val.toString();
                    }

                    if (att.getID().equalsIgnoreCase(FIELD_ACCOUNT_NAME)) {
                        // userInfo.setFIELD_ACCOUNT_NAME(value);
                        userInfo.setAccount(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_COGNOME)) {
                        // userInfo.setFIELD_COGNOME(value);
                        userInfo.setCognome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_EMAIL)) {
                        // userInfo.setFIELD_EMAIL(value);
                        userInfo.setEmail(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_GROUPS)) {
                        // userInfo.setFIELD_GROUPS(value);
                        userInfo.setGruppi(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME)) {
                        // userInfo.setFIELD_NOME(value);
                        userInfo.setNome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME_COMPLETO)) {
                        // userInfo.setFIELD_NOME_COMPLETO(value);
                        userInfo.setNomeCompleto(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME_VISUALIZZATO)) {
                        // userInfo.setFIELD_NOME_VISUALIZZATO(value);
                        // userInfo.setNome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_TEL)) {
                        // userInfo.setFIELD_TEL(value);
                        userInfo.setTel(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_UFFICIO)) {
                        // userInfo.setFIELD_UFFICIO(value);
                        userInfo.setUfficio(value);
                    }
                    // res.put(att.getID(), value);
                }

                // Attribute attr = result.get("cn");
                // if (attr != null) {
                // logger.debug("cn:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // attr = result.get("sn");
                // if (attr != null) {
                // logger.debug("sn:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // attr = result.get("mail");
                // if (attr != null) {
                // logger.debug("mail:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // // attr = result.get("uid");
                // // if (attr != null) {
                // // logger.debug("uid:");
                // // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // // }
                // //
                // // attr = result.get("userPassword");
                // // if (attr != null) {
                // // logger.debug("userPassword:");
                // // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // // }

                if (userInfo != null) {
                    res.add(userInfo);
                }
            }
        }
    } catch (NamingException ne) {
        // ne.printStackTrace();
        logger.error(ne);
        throw ne;
    } finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (Exception e) {
        }
    }

    // Azzero l'hash map
    if (!trovatiRisultati) {
        res = null;
    }

    return res;
}

From source file:com.communote.server.test.ldap.AbstractApacheDSServer.java

/**
 * Common code to get an initial context via a simple bind to the server over the wire using the
 * SUN JNDI LDAP provider. Do not use this method until after the setUp() method is called to
 * start the server otherwise it will fail.
 *
 * @param bindPrincipalDn/*from ww w  .j ava2s . c o m*/
 *            the DN of the principal to bind as
 * @param password
 *            the password of the bind principal
 * @return an LDAP context as the the administrator to the rootDSE
 * @throws Exception
 *             if the server cannot be contacted
 */
protected LdapContext getWiredContext(String bindPrincipalDn, String password) throws Exception {
    // if ( ! apacheDS.isStarted() )
    // {
    // throw new ConfigurationException( "The server is not online! Cannot connect to it." );
    // }

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, CTX_FACTORY);
    env.put(Context.PROVIDER_URL, "ldap://localhost:" + getPort());
    env.put(Context.SECURITY_PRINCIPAL, bindPrincipalDn);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    return new InitialLdapContext(env, null);
}