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.synapse.mediators.db.AbstractDBMediator.java

/**
 * Lookup the DataSource on JNDI using the specified name and optional properties
 *
 * @param dataSourceName the name of the data source to lookup
 * @param jndiProperties the JNDI properties identifying a data source provider
 * @return a DataSource looked up using the specified JNDI properties
 *///from  w  w  w  .j av a  2 s  .  c  om
private DataSource lookupDataSource(String dataSourceName, Properties jndiProperties) {

    DataSource dataSource = null;
    RepositoryBasedDataSourceFinder finder = DataSourceRepositoryHolder.getInstance()
            .getRepositoryBasedDataSourceFinder();

    if (finder.isInitialized()) {
        // first try a lookup based on the data source name only
        dataSource = finder.find(dataSourceName);
    }

    if (dataSource == null) {
        // decrypt the password if needed
        String password = jndiProperties.getProperty(Context.SECURITY_CREDENTIALS);
        if (password != null && !"".equals(password)) {
            jndiProperties.put(Context.SECURITY_CREDENTIALS, getActualPassword(password));
        }

        // lookup the data source using the specified jndi properties
        dataSource = DataSourceFinder.find(dataSourceName, jndiProperties);
        if (dataSource == null) {
            handleException("Cannot find a DataSource " + dataSourceName + " for given JNDI" + " properties :"
                    + jndiProperties);
        }
    }

    MBeanRepository mBeanRepository = DatasourceMBeanRepository.getInstance();
    Object mBean = mBeanRepository.getMBean(dataSourceName);
    if (mBean instanceof DBPoolView) {
        setDbPoolView((DBPoolView) mBean);
    }
    log.info("Successfully looked up datasource " + dataSourceName + ".");

    return dataSource;
}

From source file:gov.medicaid.dao.impl.LDAPIdentityProviderDAOBean.java

/**
 * Bind authenticate.//from   ww  w .jav  a2 s . c  om
 *
 * @param username the user to be used
 * @param password the password to be used
 * @return true if the user was authenticated
 * @throws PortalServiceException for any errors encountered
 */
public boolean authenticate(String username, String password) throws PortalServiceException {
    DirContext ctx = null;
    try {
        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, env.getProperty(Context.INITIAL_CONTEXT_FACTORY));
        props.put(Context.PROVIDER_URL, env.getProperty(Context.PROVIDER_URL));
        props.put(Context.SECURITY_PRINCIPAL, MessageFormat.format(userDNPattern, username));
        props.put(Context.SECURITY_CREDENTIALS, password);
        ctx = new InitialDirContext(props);
        return true;
    } catch (AuthenticationException authEx) {
        return false;
    } catch (NamingException e) {
        throw new PortalServiceException("Could not verify authentication results.", e);
    } finally {
        closeContext(ctx);
    }
}

From source file:jp.ikedam.jenkins.plugins.ldap_sasl.LdapSaslSecurityRealm.java

/**
 * Authorize a user./*from   w  w  w.  j a  v  a  2s .  c o m*/
 * 
 * @param username
 * @param password
 * @see hudson.security.AbstractPasswordBasedSecurityRealm#authenticate(java.lang.String, java.lang.String)
 */
@Override
protected UserDetails authenticate(String username, String password) throws AuthenticationException {
    Logger logger = getLogger();

    // check configuration.
    String ldapUris = getValidLdapUris();
    if (StringUtils.isBlank(ldapUris)) {
        logger.severe("No valid LDAP URI is specified.");
        throw new AuthenticationServiceException("No valid LDAP URI is specified.");
    }

    String mechanisms = getMechanisms();
    if (StringUtils.isBlank(mechanisms)) {
        logger.severe("No valid mechanism is specified.");
        throw new AuthenticationServiceException("No valid mechanism is specified.");
    }

    // TODO: Test with LDAPS.

    // Parameters for JNDI
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapUris);
    env.put(Context.SECURITY_PRINCIPAL, username);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.SECURITY_AUTHENTICATION, mechanisms);
    env.put("com.sun.jndi.ldap.connect.timeout", Integer.toString(getConnectionTimeout()));
    env.put("com.sun.jndi.ldap.read.timeout", Integer.toString(getReadTimeout()));

    logger.fine("Authenticating with LDAP-SASL:");
    logger.fine(String.format("username=%s", username));
    logger.fine(String.format("servers=%s", ldapUris));
    logger.fine(String.format("mech=%s", mechanisms));

    LdapContext ctx = null;
    try {
        ctx = new InitialLdapContext(env, null);
    } catch (javax.naming.AuthenticationException e) {
        // Authentication Failure...
        throw new BadCredentialsException(String.format("Authentication failed: %s", username), e);
    } catch (NamingException e) {
        // Unexpected failure...
        throw new AuthenticationServiceException(String.format("Authentication failed: %s", username), e);
    }

    String userDn = (getUserDnResolver() != null) ? getUserDnResolver().getUserDn(ctx, username) : null;
    logger.fine(String.format("User DN is %s", userDn));

    List<GrantedAuthority> authorities = (getGroupResolver() != null)
            ? getGroupResolver().resolveGroup(ctx, userDn, username)
            : new ArrayList<GrantedAuthority>();

    logger.fine("Authenticating succeeded.");
    return new LdapUser(username, "", // password(not used)
            userDn, // dn of this user.
            true, // enabled
            true, // accountNonExpired
            true, // credentialsNonExpired
            true, // accountNonLocked
            authorities.toArray(new GrantedAuthority[0]));
}

From source file:org.orbeon.oxf.processor.LDAPProcessor.java

private DirContext connect(Config config) {
    try {/*from  w  w  w  . ja v  a 2  s  . c o  m*/
        Properties env = new Properties();

        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, config.getBindDN());
        env.put(Context.SECURITY_CREDENTIALS, config.getPassword());
        env.put(LDAP_VERSION, DEFAULT_LDAP_VERSION);
        env.put(Context.INITIAL_CONTEXT_FACTORY, DEFAULT_CTX);
        env.put(Context.PROVIDER_URL, "ldap://" + config.getHost() + ":" + config.getPort());
        if (config.getReferral() != null) {
            env.put(Context.REFERRAL, config.getReferral());
        }

        if (config.getProtocol() != null)
            env.put(Context.SECURITY_PROTOCOL, config.getProtocol());
        env.put("com.sun.jndi.ldap.connect.pool", "true");

        return new InitialDirContext(env);
    } catch (NamingException e) {
        throw new OXFException("LDAP connect Failed", e);
    }
}

From source file:org.rhq.enterprise.server.resource.group.LdapGroupManagerBean.java

/**
 * @throws NamingException/* www  .j a  va2s  .  com*/
 * @see org.jboss.security.auth.spi.UsernamePasswordLoginModule#validatePassword(java.lang.String,java.lang.String)
 */
protected Set<Map<String, String>> buildGroup(Properties systemConfig, String filter) {
    Set<Map<String, String>> ret = new HashSet<Map<String, String>>();
    // Load our LDAP specific properties
    Properties env = getProperties(systemConfig);

    // Load the BaseDN
    String baseDN = (String) systemConfig.get(RHQConstants.LDAPBaseDN);

    // Load the LoginProperty
    String loginProperty = (String) systemConfig.get(RHQConstants.LDAPLoginProperty);
    if (loginProperty == null) {
        // Use the default
        loginProperty = "cn";
    }
    // Load any information we may need to bind
    String bindDN = (String) systemConfig.get(RHQConstants.LDAPBindDN);
    String bindPW = (String) systemConfig.get(RHQConstants.LDAPBindPW);
    if (bindDN != null) {
        env.setProperty(Context.SECURITY_PRINCIPAL, bindDN);
        env.setProperty(Context.SECURITY_CREDENTIALS, bindPW);
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    }
    try {
        InitialLdapContext ctx = new InitialLdapContext(env, null);
        SearchControls searchControls = getSearchControls();
        /*String filter = "(&(objectclass=groupOfUniqueNames)(uniqueMember=uid=" + userName
        + ",ou=People, dc=rhndev, dc=redhat, dc=com))";*/

        // Loop through each configured base DN.  It may be useful
        // in the future to allow for a filter to be configured for
        // each BaseDN, but for now the filter will apply to all.
        String[] baseDNs = baseDN.split(BASEDN_DELIMITER);

        for (int x = 0; x < baseDNs.length; x++) {
            NamingEnumeration<SearchResult> answer = ctx.search(baseDNs[x], filter, searchControls);
            boolean ldapApiEnumerationBugEncountered = false;
            while ((!ldapApiEnumerationBugEncountered) && answer.hasMoreElements()) {//BZ:582471- ldap api bug change
                // We use the first match
                SearchResult si = null;
                try {
                    si = answer.next();
                } catch (NullPointerException npe) {
                    ldapApiEnumerationBugEncountered = true;
                    break;
                }
                Map<String, String> entry = new HashMap<String, String>();
                String name = (String) si.getAttributes().get("cn").get();
                name = name.trim();
                Attribute desc = si.getAttributes().get("description");
                String description = desc != null ? (String) desc.get() : "";
                description = description.trim();
                entry.put("id", name);
                entry.put("name", name);
                entry.put("description", description);
                ret.add(entry);
            }
        }
    } catch (NamingException e) {
        if (e instanceof InvalidSearchFilterException) {
            InvalidSearchFilterException fException = (InvalidSearchFilterException) e;
            String message = "The ldap group filter defined is invalid ";
            log.error(message, fException);
            throw new LdapFilterException(message + " " + fException.getMessage());
        }
        //TODO: check for ldap connection/unavailable/etc. exceptions.
        else {
            log.error("LDAP communication error: " + e.getMessage(), e);
            throw new LdapCommunicationException(e);
        }
    }

    return ret;
}

From source file:org.viafirma.nucleo.validacion.CRLUtil.java

/**
 * Se conecta a la url indicada y se descarga las crls. No se esta usando
 * *******************!!! En desarrollo, no funciona
 * //from w w  w.j a  v a2  s.c o  m
 * @param hostURL
 * @return
 * @throws CRLException
 *             No se ha podido recuperar el listado
 * @throws CertificateParsingException
 */
@SuppressWarnings("unchecked")
private InputStream getIoCrlFromFNMTLDAP(X509Certificate certificadoX509)
        throws CRLException, CertificateParsingException {
    // ************************
    // recupero las propiedades para realizar la busqueda en LDAP.
    // EJ :[CN=CRL1, OU=FNMT Clase 2 CA, O=FNMT, C=ES] {2.5.4.11=FNMT Clase
    // 2 CA, 2.5.4.10=FNMT, 2.5.4.6=ES, 2.5.4.3=CRL1}
    Map<String, String> propiedades = new HashMap<String, String>();
    try {
        log.debug("Recuperando puntos de distribucin CRL del certificado FNMT: "
                + certificadoX509.getIssuerDN());
        // recupero la extensin OID 2.5.29.31 ( id-ce-cRLDistributionPoinds
        // segun el RFC 3280 seccin 4.2.1.14)
        byte[] val1 = certificadoX509.getExtensionValue(OID_CRLS);
        if (val1 == null) {
            log.debug("   El certificado NO tiene punto de distribucin de CRL ");
        } else {
            ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(val1));
            DERObject derObj = oAsnInStream.readObject();
            DEROctetString dos = (DEROctetString) derObj;
            byte[] val2 = dos.getOctets();
            ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(val2));
            DERObject derObj2 = oAsnInStream2.readObject();

            X509Handler.getCurrentInstance().readPropiedadesOid(OID_CRLS, derObj2, propiedades);

        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new CertificateParsingException(e.toString());
    }

    // comprobamos la configuracin
    if (isSomeFNMTValorNull()) {
        throw new CRLException(
                "Para el acceso a las CRLs de la FNMT es necesario las credenciales. Indique el parametro de configuracin :"
                        + Constantes.CONEXION_LDAP_CRL_FNMT);
    }

    String CN = "CN=" + propiedades.get(FNMT_CN_IDENTIFICADOR) + "," + certificadoX509.getIssuerDN();
    log.debug("Buscando en el LDAP " + CN);

    // **********************************************
    // Nos conectamos al LDAP para recuperar la CRLs.

    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, fnmtLDAPHostURL);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, fnmtPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, fnmtCredencial);
    env.put(Context.REFERRAL, "follow");

    try {
        DirContext ctx = new InitialDirContext(env);
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        NamingEnumeration namings = (ctx.search(CN, "(objectclass=*)", searchControls));

        log.debug("Se ha logrado conectar al LDAP");

        if (namings.hasMore()) {
            log.debug("Recuperando el contenido de la CRLs");
            // recupero el resultado
            SearchResult resultado = ((SearchResult) namings.next());

            // recupero todos los atributos del resultado
            Attributes avals = resultado.getAttributes();

            // recupero los bytes.
            byte[] bytes;
            if ((avals.get("certificateRevocationList;binary")) != null) {
                log.debug("Atributos deben estar en binario");
                Attribute atributo = (avals.get("certificateRevocationList;binary"));
                bytes = ((byte[]) atributo.get());
            } else {
                log.debug("Atributos en exadecimal En Hexadecimal");
                Attribute atributo = (avals.get("certificateRevocationList"));
                bytes = ((byte[]) atributo.get());
                log.debug("Por implementar");
            }

            if (bytes != null) {
                ByteArrayInputStream io = new ByteArrayInputStream(bytes);
                return io;
            }
        }
    } catch (NamingException e) {
        log.error("No se puede conectar al LDAP!!", e);
    }
    return null;
}

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

/**
 * Set next free uidNumber.//from   w w w  .j ava 2  s.  co  m
 */
private void setNextUidNumber() {
    Hashtable<String, String> env = getLdapConnectionSettings();
    env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
    env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));
    DirContext ctx;

    try {
        ctx = new InitialDirContext(env);
        Attributes attrs = ctx.getAttributes(ConfigCore.getParameter("ldap_nextFreeUnixId"));
        Attribute la = attrs.get("uidNumber");
        String oldValue = (String) la.get(0);
        int bla = Integer.parseInt(oldValue) + 1;

        BasicAttribute attrNeu = new BasicAttribute("uidNumber", String.valueOf(bla));
        ModificationItem[] mods = new ModificationItem[1];
        mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attrNeu);
        ctx.modifyAttributes(ConfigCore.getParameter("ldap_nextFreeUnixId"), mods);

        ctx.close();
    } catch (NamingException e) {
        logger.error(e);
    }

}

From source file:org.apache.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java

protected DirContext open() throws NamingException {
    if (context != null) {
        return context;
    }//from   w ww .  ja  va2 s . c  om
    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  a  2 s . 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());
    }/*from ww  w .ja v  a 2s. c  o  m*/
    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);
        }
    }
}