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.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");
    }/* ww  w  . jav  a2  s  . c o  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.");
    }// ww w .j a va2  s.c om
    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
 * //from   w  w  w . java2s .  co 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.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  w w  . j  av a 2  s.  c  o m
    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.jboss.additional.testsuite.jdkall.present.elytron.sasl.OtpSaslTestCase.java

/**
 * Check correct user attribute values in the LDAP when using OTP algorithm.
 *///w  ww.  j ava  2s . com
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: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 a v  a  2  s.com*/
 *            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);
}

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

/**
 * @param args/* w  w w.  ja va 2s. 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:org.nuxeo.ecm.directory.ldap.MockLdapServer.java

public void startLdapServer() {
    cfg = new MutableStartupConfiguration();
    cfg.setWorkingDirectory(workingDir);

    log.debug("Working directory is " + workingDir.getAbsolutePath());

    Properties env = new Properties();

    env.setProperty(Context.PROVIDER_URL, BASE_DN);
    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName());
    env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    env.setProperty(Context.SECURITY_PRINCIPAL, PartitionNexus.ADMIN_PRINCIPAL);
    env.setProperty(Context.SECURITY_CREDENTIALS, PartitionNexus.ADMIN_PASSWORD);

    try {/*ww  w  .  j av  a  2  s .co  m*/
        initConfiguration();
        env.putAll(cfg.toJndiEnvironment());
        serverContext = new InitialDirContext(env);
    } catch (NamingException e) {
        log.error("Failed to start Apache DS: ", e);
    }
}

From source file:org.springframework.ldap.samples.article.dao.TraditionalPersonDaoImpl.java

private DirContext createAuthenticatedContext() {
    Hashtable env = new Hashtable();
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, userName);
    env.put(Context.SECURITY_CREDENTIALS, password);
    return createContext(env);
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Opens a connection to Active Directory by establishing an initial LDAP
 * context.  The security principal and credentials are assigned the
 * account name and password parameters.
 *
 * @param anAcountDN Active Directory account name (DN format).
 * @param anAccountPassword Active Directory account password.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 *//* w  w  w .  ja v a  2 s  .co m*/
@SuppressWarnings("unchecked")
public void open(String anAcountDN, String anAccountPassword) throws NSException {
    Logger appLogger = mAppMgr.getLogger(this, "open");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    // LDAP Reference - http://docs.oracle.com/javase/1.5.0/docs/guide/jndi/jndi-ldap-gl.html

    Hashtable<String, String> environmentalVariables = new Hashtable<String, String>();
    environmentalVariables.put("com.sun.jndi.ldap.connect.pool", StrUtl.STRING_TRUE);
    environmentalVariables.put(Context.PROVIDER_URL, getPropertyValue("domain_url", null));
    environmentalVariables.put("java.naming.ldap.attributes.binary", "tokenGroups objectSid");
    environmentalVariables.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    environmentalVariables.put(Context.SECURITY_PRINCIPAL, anAcountDN);
    environmentalVariables.put(Context.SECURITY_CREDENTIALS, anAccountPassword);

    // Referral options: follow, throw, ignore (default)

    environmentalVariables.put(Context.REFERRAL, getPropertyValue("referral_handling", "ignore"));

    // Authentication options: simple, DIGEST-MD5 CRAM-MD5

    environmentalVariables.put(Context.SECURITY_AUTHENTICATION, getPropertyValue("authentication", "simple"));

    try {
        mLdapContext = new InitialLdapContext(environmentalVariables, null);
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Context Error: %s", e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}