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:org.apache.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java

protected DirContext open() throws NamingException {
    if (context != null) {
        return context;
    }/*w  ww . ja va2s  .  co  m*/
    try {
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
        if (connectionUsername != null || !"".equals(connectionUsername)) {
            env.put(Context.SECURITY_PRINCIPAL, connectionUsername);
        }
        if (connectionPassword != null || !"".equals(connectionPassword)) {
            env.put(Context.SECURITY_CREDENTIALS, connectionPassword);
        }
        env.put(Context.SECURITY_PROTOCOL, connectionProtocol == null ? "" : connectionProtocol);
        env.put(Context.PROVIDER_URL, connectionURL == null ? "" : connectionURL);
        env.put(Context.SECURITY_AUTHENTICATION, authentication == null ? "" : authentication);
        context = new InitialDirContext(env);

    } catch (NamingException e) {
        log.error(e);
        throw e;
    }
    return context;
}

From source file:org.hyperic.hq.plugin.jboss.JBossDetector.java

public List<ServerResource> getServerList(String installpath, long pid) throws PluginException {
    File configDir = new File(installpath);
    getLog().debug("[getServerList] configDir='" + configDir + "'");
    File serviceXML = new File(configDir, JBOSS_SERVICE_XML);
    File distDir = configDir.getParentFile().getParentFile();

    // jboss copies the config set into the tmp deploy dir
    if (distDir.getName().equals("deploy")) {
        return null;
    }/*from  w  w w  .j a  v a2s. c o  m*/

    String serverName = configDir.getName();

    String fullVersion = getVersion(configDir, "jboss-j2ee.jar");

    // 5.0
    if (fullVersion == null) {
        fullVersion = getVersion(configDir.getParentFile().getParentFile(), "jboss-j2se.jar");
    }
    if (fullVersion == null) {
        getLog().debug("unable to determine JBoss version in: " + configDir);
        return null;
    }

    String typeVersion = fullVersion.substring(0, 3);

    if (!getTypeInfo().getVersion().equals(typeVersion)) {
        getLog().debug(configDir + " (" + fullVersion + ")" + " is not a " + getName());
        return null;
    }

    getLog().debug("discovered JBoss server [" + serverName + "] in " + configDir);

    ConfigResponse _config = new ConfigResponse();
    ConfigResponse controlConfig = new ConfigResponse();
    ConfigResponse metricConfig = new ConfigResponse();

    JBossConfig cfg = JBossConfig.getConfig(serviceXML);

    String address = getBindAddress(cfg, installpath);

    String jnpUrl = "jnp://" + address + ":" + cfg.getJnpPort();
    getLog().debug("JNP url=" + jnpUrl);

    _config.setValue(Context.PROVIDER_URL, jnpUrl);

    //for use w/ -jar hq-pdk.jar or agent.properties
    Properties props = getManager().getProperties();
    String[] credProps = { Context.PROVIDER_URL, Context.SECURITY_PRINCIPAL, Context.SECURITY_CREDENTIALS };
    for (int i = 0; i < credProps.length; i++) {
        String value = props.getProperty(credProps[i]);
        if (value != null) {
            _config.setValue(credProps[i], value);
        }
    }

    String script = distDir + File.separator + JBossServerControlPlugin.getControlScript(isWin32());

    controlConfig.setValue(ServerControlPlugin.PROP_PROGRAM, getCanonicalPath(script));

    controlConfig.setValue(JBossServerControlPlugin.PROP_CONFIGSET, serverName);

    String logDir = ".." + File.separator + ".." + File.separator + ".." + File.separator + "logs";
    File brandedLogDir = new File(installpath, logDir);

    if (!brandedLogDir.exists()) {
        logDir = "log";
    }

    metricConfig.setValue(Log4JLogTrackPlugin.PROP_FILES_SERVER, logDir + File.separator + "server.log");

    ServerResource server = createServerResource(installpath);

    server.setConnectProperties(new String[] { Context.PROVIDER_URL });
    if (pid > 0) {
        populateListeningPorts(pid, _config, true);
    }

    server.setProductConfig(_config);
    server.setMeasurementConfig(metricConfig);
    server.setControlConfig(controlConfig);

    if (JBossProductPlugin.isBrandedServer(configDir, getPluginProperty("brand.ear"))) {
        // Branded JBoss
        String brandName = getPluginProperty("brand.name");
        server.setName(getPlatformName() + " " + brandName);
        server.setIdentifier(brandName);
    } else {
        server.setName(server.getName() + " " + serverName);
    }

    File home = cfg.getJBossHome();
    if (home != null) {
        //normally setup in JBossProductPlugin
        //this handles the case of the agent being started
        //before the JBoss server
        adjustClassPath(home.getPath());
    }
    //pickup any jars found relative to this installpath
    adjustClassPath(installpath);

    List<ServerResource> servers = new ArrayList<ServerResource>();
    //apply externally defined AUTOINVENTORY_NAME, etc.
    if (pid > 0) {
        discoverServerConfig(server, pid);
    }
    servers.add(server);

    return servers;
}

From source file:org.alfresco.repo.security.authentication.ldap.LDAPInitialDirContextFactoryImpl.java

public void afterPropertiesSet() throws Exception {
    logger.debug("after Properties Set");
    // Check Anonymous bind

    Hashtable<String, String> env = new Hashtable<String, String>(authenticatedEnvironment.size());
    env.putAll(authenticatedEnvironment);
    env.remove(Context.SECURITY_PRINCIPAL);
    env.remove(Context.SECURITY_CREDENTIALS);
    if (isSSLSocketFactoryRequired()) {
        KeyStore trustStore = initTrustStore();
        AlfrescoSSLSocketFactory.initTrustedSSLSocketFactory(trustStore);
        env.put("java.naming.ldap.factory.socket", AlfrescoSSLSocketFactory.class.getName());
    }/* w  ww .j  a va2 s.  com*/
    try {
        new InitialDirContext(env);

        logger.warn("LDAP server supports anonymous bind " + env.get(Context.PROVIDER_URL));
    } catch (javax.naming.AuthenticationException ax) {

    } catch (AuthenticationNotSupportedException e) {

    } catch (NamingException nx) {
        logger.error("Unable to connect to LDAP Server; check LDAP configuration", nx);
        return;
    }

    // Simple DN and password

    env = new Hashtable<String, String>(authenticatedEnvironment.size());
    env.putAll(authenticatedEnvironment);
    env.put(Context.SECURITY_PRINCIPAL, "daftAsABrush");
    env.put(Context.SECURITY_CREDENTIALS, "daftAsABrush");
    if (isSSLSocketFactoryRequired()) {
        KeyStore trustStore = initTrustStore();
        AlfrescoSSLSocketFactory.initTrustedSSLSocketFactory(trustStore);
        env.put("java.naming.ldap.factory.socket", AlfrescoSSLSocketFactory.class.getName());
    }
    try {

        new InitialDirContext(env);

        throw new AuthenticationException("The ldap server at " + env.get(Context.PROVIDER_URL)
                + " falls back to use anonymous bind if invalid security credentials are presented. This is not supported.");
    } catch (javax.naming.AuthenticationException ax) {
        logger.info("LDAP server does not fall back to anonymous bind for a string uid and password at "
                + env.get(Context.PROVIDER_URL));
    } catch (AuthenticationNotSupportedException e) {
        logger.info("LDAP server does not fall back to anonymous bind for a string uid and password at "
                + env.get(Context.PROVIDER_URL));
    } catch (NamingException nx) {
        logger.info("LDAP server does not support simple string user ids and invalid credentials at "
                + env.get(Context.PROVIDER_URL));
    }

    // DN and password

    env = new Hashtable<String, String>(authenticatedEnvironment.size());
    env.putAll(authenticatedEnvironment);
    env.put(Context.SECURITY_PRINCIPAL, "cn=daftAsABrush,dc=woof");
    env.put(Context.SECURITY_CREDENTIALS, "daftAsABrush");
    if (isSSLSocketFactoryRequired()) {
        KeyStore trustStore = initTrustStore();
        AlfrescoSSLSocketFactory.initTrustedSSLSocketFactory(trustStore);
        env.put("java.naming.ldap.factory.socket", AlfrescoSSLSocketFactory.class.getName());
    }
    try {

        new InitialDirContext(env);

        throw new AuthenticationException("The ldap server at " + env.get(Context.PROVIDER_URL)
                + " falls back to use anonymous bind if invalid security credentials are presented. This is not supported.");
    } catch (javax.naming.AuthenticationException ax) {
        logger.info("LDAP server does not fall back to anonymous bind for a simple dn and password at "
                + env.get(Context.PROVIDER_URL));
    } catch (AuthenticationNotSupportedException e) {
        logger.info("LDAP server does not fall back to anonymous bind for a simple dn and password at "
                + env.get(Context.PROVIDER_URL));
    } catch (NamingException nx) {
        logger.info("LDAP server does not support simple DN and invalid password at "
                + env.get(Context.PROVIDER_URL));
    }

    // Check more if we have a real principal we expect to work

    String principal = defaultEnvironment.get(Context.SECURITY_PRINCIPAL);
    if (principal != null) {
        // Correct principal invalid password

        env = new Hashtable<String, String>(authenticatedEnvironment.size());
        env.putAll(authenticatedEnvironment);
        env.put(Context.SECURITY_PRINCIPAL, principal);
        env.put(Context.SECURITY_CREDENTIALS, "sdasdasdasdasd123123123");
        if (isSSLSocketFactoryRequired()) {
            KeyStore trustStore = initTrustStore();
            AlfrescoSSLSocketFactory.initTrustedSSLSocketFactory(trustStore);
            env.put("java.naming.ldap.factory.socket", AlfrescoSSLSocketFactory.class.getName());
        }
        if (!checkedEnvs.contains(env)) {

            try {

                new InitialDirContext(env);

                throw new AuthenticationException("The ldap server at " + env.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 (javax.naming.AuthenticationException ax) {
                logger.info(
                        "LDAP server does not fall back to anonymous bind for known principal and invalid credentials at "
                                + env.get(Context.PROVIDER_URL));
            } catch (AuthenticationNotSupportedException e) {
                logger.info("LDAP server does not support the required authentication mechanism");
            } catch (NamingException nx) {
                // already done
            }
            // Record this environment as checked so that we don't check it again on further restarts / other subsystem
            // instances
            checkedEnvs.add(env);
        }
    }
}

From source file:com.alfaariss.oa.engine.attribute.gather.processor.jndi.JNDIGatherer.java

/**
 * Reads JNDI connection information from the configuration.
 * <br>/*from w w  w.j  a  v  a  2  s .c  om*/
 * Creates an <code>Hashtable</code> containing the JNDI environment variables.
 * @param oConfigurationManager The configuration manager
 * @param eConfig the configuration section
 * @return <code>DirContext</code> that contains the JNDI connection
 * @throws AttributeException if configuration reading fails
 */
private Hashtable<String, String> readJNDIContext(IConfigurationManager oConfigurationManager, Element eConfig)
        throws AttributeException {
    Hashtable<String, String> htEnvironment = new Hashtable<String, String>(11);

    try {
        Element eSecurityPrincipal = oConfigurationManager.getSection(eConfig, "security_principal");
        if (eSecurityPrincipal == null) {
            _logger.error("No 'security_principal' section found in 'resource' configuration");
            throw new AttributeException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sPrincipal = oConfigurationManager.getParam(eSecurityPrincipal, "dn");
        if (sPrincipal == null) {
            _logger.error("No item 'dn' item found in configuration");
            throw new AttributeException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sPassword = oConfigurationManager.getParam(eSecurityPrincipal, "password");
        if (sPassword == null) {
            _logger.error("No 'password' item found in configuration ");
            throw new AttributeException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sDriver = oConfigurationManager.getParam(eConfig, "driver");
        if (sDriver == null) {
            _logger.error("No 'driver' item found in configuration");
            throw new AttributeException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sUrl = oConfigurationManager.getParam(eConfig, "url");
        if (sUrl == null) {
            _logger.error("No valid config item 'url' found in configuration");
            throw new AttributeException(SystemErrors.ERROR_CONFIG_READ);
        }

        if (sUrl.length() >= 5 && sUrl.substring(0, 5).equalsIgnoreCase("ldaps")) {
            // Request SSL transport
            htEnvironment.put(Context.SECURITY_PROTOCOL, "ssl");
            _logger.info("SSL enabled");
        } else {
            _logger.info("SSL disabled");
        }

        htEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, sDriver);
        htEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple");
        htEnvironment.put(Context.SECURITY_PRINCIPAL, sPrincipal);
        htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword);
        htEnvironment.put(Context.PROVIDER_URL, sUrl);
    } catch (AttributeException e) {
        throw e;
    } catch (Exception e) {
        _logger.error("Could not create a connection", e);
        throw new AttributeException(SystemErrors.ERROR_INTERNAL);
    }
    return htEnvironment;
}

From source file:org.apache.ambari.server.serveraction.kerberos.ADKerberosOperationHandler.java

/**
 * Helper method to create the LDAP context needed to interact with the Active Directory.
 *
 * @return the relevant LdapContext//from   w w  w .j  a  va2 s  .  co  m
 * @throws KerberosKDCConnectionException       if a connection to the KDC cannot be made
 * @throws KerberosAdminAuthenticationException if the administrator credentials fail to authenticate
 * @throws KerberosRealmException               if the realm does not map to a KDC
 * @throws KerberosOperationException           if an unexpected error occurred
 */
protected LdapContext createLdapContext() throws KerberosOperationException {
    KerberosCredential administratorCredentials = getAdministratorCredentials();

    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_CONTEXT_FACTORY_CLASS);
    properties.put(Context.PROVIDER_URL, ldapUrl);
    properties.put(Context.SECURITY_PRINCIPAL, administratorCredentials.getPrincipal());
    properties.put(Context.SECURITY_CREDENTIALS, administratorCredentials.getPassword());
    properties.put(Context.SECURITY_AUTHENTICATION, "simple");
    properties.put(Context.REFERRAL, "follow");
    properties.put("java.naming.ldap.factory.socket", TrustingSSLSocketFactory.class.getName());

    try {
        return createInitialLdapContext(properties, null);
    } catch (CommunicationException e) {
        String message = String.format("Failed to communicate with the Active Directory at %s: %s", ldapUrl,
                e.getMessage());
        LOG.warn(message, e);
        throw new KerberosKDCConnectionException(message, e);
    } catch (AuthenticationException e) {
        String message = String.format("Failed to authenticate with the Active Directory at %s: %s", ldapUrl,
                e.getMessage());
        LOG.warn(message, e);
        throw new KerberosAdminAuthenticationException(message, e);
    } catch (NamingException e) {
        String error = e.getMessage();

        if ((error != null) && !error.isEmpty()) {
            String message = String.format("Failed to communicate with the Active Directory at %s: %s", ldapUrl,
                    e.getMessage());
            LOG.warn(message, e);

            if (error.startsWith("Cannot parse url:")) {
                throw new KerberosKDCConnectionException(message, e);
            } else {
                throw new KerberosOperationException(message, e);
            }
        } else {
            throw new KerberosOperationException("Unexpected error condition", e);
        }
    }
}

From source file:org.apache.syncope.fit.core.reference.AbstractITCase.java

@SuppressWarnings({ "unchecked", "rawtypes", "UseOfObsoleteCollectionType" })
protected InitialDirContext getLdapResourceDirContext(final String bindDn, final String bindPwd)
        throws NamingException {
    ResourceTO ldapRes = resourceService.read(RESOURCE_NAME_LDAP);
    final Map<String, ConnConfProperty> ldapConnConf = connectorService.read(ldapRes.getConnector())
            .getConfigurationMap();//from   w w w .jav  a 2s .  c  om

    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://" + ldapConnConf.get("host").getValues().get(0) + ":"
            + ldapConnConf.get("port").getValues().get(0) + "/");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL,
            bindDn == null ? ldapConnConf.get("principal").getValues().get(0) : bindDn);
    env.put(Context.SECURITY_CREDENTIALS,
            bindPwd == null ? ldapConnConf.get("credentials").getValues().get(0) : bindPwd);

    return new InitialDirContext(env);
}

From source file:de.sub.goobi.helper.ldap.Ldap.java

/**
 * change password of given user, needs old password for authentication.
 *
 * @param inUser//from  w  w w .j av  a  2 s  .  c o m
 *            User object
 * @param inOldPassword
 *            String
 * @param inNewPassword
 *            String
 * @return boolean about result of change
 */
public boolean changeUserPassword(User inUser, String inOldPassword, String inNewPassword)
        throws NoSuchAlgorithmException {
    MD4 digester = new MD4();
    Hashtable<String, String> env = getLdapConnectionSettings();
    if (!ConfigCore.getBooleanParameter("ldap_readonly", false)) {
        env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
        env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));

        try {
            DirContext ctx = new InitialDirContext(env);

            /*
             * Encryption of password and Base64-Encoding
             */
            MessageDigest md = MessageDigest.getInstance(ConfigCore.getParameter("ldap_encryption", "SHA"));
            md.update(inNewPassword.getBytes(StandardCharsets.UTF_8));
            String digestBase64 = new String(Base64.encodeBase64(md.digest()), StandardCharsets.UTF_8);
            ModificationItem[] mods = new ModificationItem[4];

            /*
             * UserPasswort-Attribut ndern
             */
            BasicAttribute userpassword = new BasicAttribute("userPassword",
                    "{" + ConfigCore.getParameter("ldap_encryption", "SHA") + "}" + digestBase64);

            /*
             * LanMgr-Passwort-Attribut ndern
             */
            BasicAttribute lanmgrpassword = null;
            try {
                lanmgrpassword = new BasicAttribute("sambaLMPassword",
                        LdapUser.toHexString(LdapUser.lmHash(inNewPassword)));
                // TODO: Don't catch super class exception, make sure that
                // the password isn't logged here
            } catch (Exception e) {
                logger.error(e);
            }

            /*
             * NTLM-Passwort-Attribut ndern
             */
            BasicAttribute ntlmpassword = null;
            try {
                byte hmm[] = digester.digest(inNewPassword.getBytes("UnicodeLittleUnmarked"));
                ntlmpassword = new BasicAttribute("sambaNTPassword", LdapUser.toHexString(hmm));
            } catch (UnsupportedEncodingException e) {
                // TODO: Make sure that the password isn't logged here
                logger.error(e);
            }

            BasicAttribute sambaPwdLastSet = new BasicAttribute("sambaPwdLastSet",
                    String.valueOf(System.currentTimeMillis() / 1000l));

            mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userpassword);
            mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, lanmgrpassword);
            mods[2] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, ntlmpassword);
            mods[3] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, sambaPwdLastSet);
            ctx.modifyAttributes(getUserDN(inUser), mods);

            // Close the context when we're done
            ctx.close();
            return true;
        } catch (NamingException e) {
            logger.debug("Benutzeranmeldung nicht korrekt oder Passwortnderung nicht mglich", e);
            return false;
        }
    }
    return false;
}

From source file:org.apache.james.user.ldap.ReadOnlyUsersLDAPRepository.java

protected Properties getContextEnvironment() {
    final Properties props = new Properties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
    props.put(Context.PROVIDER_URL, null == ldapHost ? "" : ldapHost);
    if (null == credentials || credentials.isEmpty()) {
        props.put(Context.SECURITY_AUTHENTICATION, LdapConstants.SECURITY_AUTHENTICATION_NONE);
    } else {//  w  w w.jav  a 2  s . co  m
        props.put(Context.SECURITY_AUTHENTICATION, LdapConstants.SECURITY_AUTHENTICATION_SIMPLE);
        props.put(Context.SECURITY_PRINCIPAL, null == principal ? "" : principal);
        props.put(Context.SECURITY_CREDENTIALS, credentials);
    }
    // The following properties are specific to com.sun.jndi.ldap.LdapCtxFactory
    props.put(PROPERTY_NAME_CONNECTION_POOL, Boolean.toString(useConnectionPool));
    if (connectionTimeout > -1) {
        props.put(PROPERTY_NAME_CONNECT_TIMEOUT, Integer.toString(connectionTimeout));
    }
    if (readTimeout > -1) {
        props.put(PROPERTY_NAME_READ_TIMEOUT, Integer.toString(readTimeout));
    }
    return props;
}

From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java

/**
 * Reads JNDI connection information from the configuration.
 * <br>/*  w w w  . j  a v  a  2s . c  o  m*/
 * Creates an <code>Hashtable</code> containing the JNDI environment variables.
 * @param oConfigurationManager The configuration manager
 * @param eConfig the configuration section
 * @return <code>DirContext</code> that contains the JNDI connection
 * @throws UserException if configuration reading fails
 */
private Hashtable<String, String> readJNDIContext(IConfigurationManager oConfigurationManager, Element eConfig)
        throws UserException {
    Hashtable<String, String> htEnvironment = new Hashtable<String, String>();

    try {
        Element eSecurityPrincipal = oConfigurationManager.getSection(eConfig, "security_principal");
        if (eSecurityPrincipal == null) {
            _logger.error("No 'security_principal' section found in 'resource' configuration");
            throw new UserException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sPrincipal = oConfigurationManager.getParam(eSecurityPrincipal, "dn");
        if (sPrincipal == null) {
            _logger.error("No item 'dn' item found in configuration");
            throw new UserException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sPassword = oConfigurationManager.getParam(eSecurityPrincipal, "password");
        if (sPassword == null) {
            _logger.error("No 'password' item found in configuration ");
            throw new UserException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sDriver = oConfigurationManager.getParam(eConfig, "driver");
        if (sDriver == null) {
            _logger.error("No 'driver' item found in configuration");
            throw new UserException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sUrl = oConfigurationManager.getParam(eConfig, "url");
        if (sUrl == null) {
            _logger.error("No valid config item 'url' found in configuration");
            throw new UserException(SystemErrors.ERROR_CONFIG_READ);
        }

        if (sUrl.length() >= 5 && sUrl.substring(0, 5).equalsIgnoreCase("ldaps")) {
            // Request SSL transport
            htEnvironment.put(Context.SECURITY_PROTOCOL, "ssl");
            _logger.info("SSL enabled");
        } else {
            _logger.info("SSL disabled");
        }

        htEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, sDriver);
        htEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple");
        htEnvironment.put(Context.SECURITY_PRINCIPAL, sPrincipal);
        htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword);
        htEnvironment.put(Context.PROVIDER_URL, sUrl);

    } catch (UserException e) {
        throw e;
    } catch (Exception e) {
        _logger.error("Could not create a connection", e);
        throw new UserException(SystemErrors.ERROR_INTERNAL, e);
    }
    return htEnvironment;
}

From source file:org.springframework.security.ldap.userdetails.LdapUserDetailsManager.java

private void changePasswordUsingAttributeModification(DistinguishedName userDn, String oldPassword,
        String newPassword) {/*from  w w w .  j a  v  a2  s.  c o  m*/

    final ModificationItem[] passwordChange = new ModificationItem[] { new ModificationItem(
            DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(passwordAttributeName, newPassword)) };

    if (oldPassword == null) {
        template.modifyAttributes(userDn, passwordChange);
        return;
    }

    template.executeReadWrite(dirCtx -> {
        LdapContext ctx = (LdapContext) dirCtx;
        ctx.removeFromEnvironment("com.sun.jndi.ldap.connect.pool");
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, LdapUtils.getFullDn(userDn, ctx).toString());
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, oldPassword);
        // TODO: reconnect doesn't appear to actually change the credentials
        try {
            ctx.reconnect(null);
        } catch (javax.naming.AuthenticationException e) {
            throw new BadCredentialsException("Authentication for password change failed.");
        }

        ctx.modifyAttributes(userDn, passwordChange);

        return null;
    });

}