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:de.sub.goobi.helper.ldap.Ldap.java

/**
 * retrieve home directory of given user.
 *
 * @param inBenutzer//from  w w w.  ja v a2 s. c o m
 *            User object
 * @return path as string
 */
public String getUserHomeDirectory(User inBenutzer) {
    if (ConfigCore.getBooleanParameter("useLocalDirectory", false)) {
        return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin();
    }
    Hashtable<String, String> env = getLdapConnectionSettings();
    if (ConfigCore.getBooleanParameter("ldap_useTLS", false)) {

        env = new Hashtable<>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ConfigCore.getParameter("ldap_url"));
        env.put("java.naming.ldap.version", "3");
        LdapContext ctx = null;
        StartTlsResponse tls = null;
        try {
            ctx = new InitialLdapContext(env, null);

            // Authentication must be performed over a secure channel
            tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
            tls.negotiate();

            // Authenticate via SASL EXTERNAL mechanism using client X.509
            // certificate contained in JVM keystore
            ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));

            ctx.reconnect(null);

            Attributes attrs = ctx.getAttributes(getUserDN(inBenutzer));
            Attribute la = attrs.get("homeDirectory");
            return (String) la.get(0);

            // Perform search for privileged attributes under authenticated
            // context

        } catch (IOException e) {
            logger.error("TLS negotiation error:", e);

            return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin();
        } catch (NamingException e) {

            logger.error("JNDI error:", e);

            return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin();
        } finally {
            if (tls != null) {
                try {
                    // Tear down TLS connection
                    tls.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
            if (ctx != null) {
                try {
                    // Close LDAP connection
                    ctx.close();
                } catch (NamingException e) {
                    logger.error(e);
                }
            }
        }
    } else if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) {
        env.put(Context.SECURITY_AUTHENTICATION, "none");
    } else {
        env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
        env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));

    }
    DirContext ctx;
    String rueckgabe = "";
    try {
        ctx = new InitialDirContext(env);
        Attributes attrs = ctx.getAttributes(getUserDN(inBenutzer));
        Attribute la = attrs.get("homeDirectory");
        rueckgabe = (String) la.get(0);
        ctx.close();
    } catch (NamingException e) {
        logger.error(e);
    }
    return rueckgabe;
}

From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java

private boolean bindSearchX(String username, String password, Hashtable<String, String> env, boolean bind)
        throws AuthenticationException, NamingException {

    env.put(Context.SECURITY_PRINCIPAL, ldapSecurityPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, ldapSecurityCredentials);

    DirContext ctx = null;/*from  ww  w  . ja  v a2  s  . c  o  m*/
    try {
        ctx = new InitialDirContext(env);
    } catch (NamingException ne) {
        log.error("Failed to bind as: {}", ldapSecurityPrincipal);
    }

    // ensure we have the userPassword attribute at a minimum
    String[] attributeList = new String[] { "userPassword" };

    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(attributeList);
    sc.setDerefLinkFlag(true);
    sc.setReturningObjFlag(false);
    sc.setTimeLimit(5000);

    String filter = "(" + filterPrefix + idAttr + "=" + username + filterSuffix + ")";
    // Do the search
    NamingEnumeration<SearchResult> results = ctx.search(baseDn, filter, sc);
    if (!results.hasMore()) {
        log.warn("no valid user found.");
        return false;
    }

    SearchResult result = results.next();
    log.debug("authenticating user: {}", result.getNameInNamespace());

    if (bind) {
        // setup user context for binding
        Hashtable<String, String> userEnv = new Hashtable<String, String>();
        userEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        userEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
        userEnv.put(Context.PROVIDER_URL, baseUrl);
        userEnv.put(Context.SECURITY_PRINCIPAL, result.getNameInNamespace());
        userEnv.put(Context.SECURITY_CREDENTIALS, password);

        try {
            new InitialDirContext(userEnv);
        } catch (NamingException ne) {
            log.error("failed to authenticate user: " + result.getNameInNamespace());
            throw ne;
        }
    } else {
        // get userPassword attribute
        Attribute up = result.getAttributes().get("userPassword");
        if (up == null) {
            log.error("unable to read userPassword attribute for: {}", result.getNameInNamespace());
            return false;
        }

        byte[] userPasswordBytes = (byte[]) up.get();
        String userPassword = new String(userPasswordBytes);

        // compare passwords - also handles encodings
        if (!passwordsMatch(password, userPassword)) {
            return false;
        }
    }

    return true;
}

From source file:org.openiam.spml2.spi.ldap.LdapConnectorImpl.java

public LdapContext connect(String userName, String password) {

    //LdapContext ctxLdap = null;
    Hashtable<String, String> envDC = new Hashtable();

    //keystore = secres.getString("KEYSTORE");
    System.setProperty("javax.net.ssl.trustStore", keystore);

    log.debug("Connecting to ldap using principal=" + userName);

    //envDC.put(Context.PROVIDER_URL,host);
    envDC.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    envDC.put(Context.SECURITY_AUTHENTICATION, "simple"); // simple
    envDC.put(Context.SECURITY_PRINCIPAL, userName); //"administrator@diamelle.local"
    envDC.put(Context.SECURITY_CREDENTIALS, password);
    //   if (protocol != null && protocol.equalsIgnoreCase("SSL")) {
    //      envDC.put(Context.SECURITY_PROTOCOL, protocol);
    //   }/* www. java  2 s . c o  m*/

    try {
        return (new InitialLdapContext(envDC, null));
    } catch (NamingException ne) {
        log.error(ne.getMessage());

    }
    return null;
}

From source file:com.aurel.track.util.LdapUtil.java

/**
 * Gets the initial context/*from   ww  w  . ja va 2  s . c  o m*/
 * 
 * @param providerUrl
 * @param bindDN
 * @param bindPassword
 * @return
 */
public static LdapContext getInitialContext(String providerUrl, String bindDN, String bindPassword) {
    List<String> trace = new ArrayList<String>();
    LOGGER.debug("providerURL: " + providerUrl);
    trace.add("Attempting to connect to the LDAP server...");
    if (providerUrl != null && providerUrl.startsWith("ldaps:")) {
        System.setProperty("javax.net.ssl.trustStore", PATH_TO_KEY_STORE);
        trace.add("Using ldaps: with keystore at " + PATH_TO_KEY_STORE);
        File ks = new File(PATH_TO_KEY_STORE);
        if (!ks.exists()) {
            trace.add("*** There is no keystore at " + PATH_TO_KEY_STORE);
        }
    }
    if (providerUrl == null) {
        LOGGER.warn("LDAP provider URL should not be null.");
        return null;
    }
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    if (LOGGER.isDebugEnabled()) {
        env.put("com.sun.jndi.ldape.trace.ber", System.err);
    }
    env.put("java.naming.ldap.version", "3");
    env.put("com.sun.jndi.ldap.connect.timeout", "10000");
    env.put("com.sun.jndi.dns.timeout.initial", "2000");
    env.put("com.sun.jndi.dns.timeout.retries", "3");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, providerUrl);
    if ((bindDN != null) && !bindDN.equals("")) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, bindDN);
        env.put(Context.SECURITY_CREDENTIALS, bindPassword);
        LOGGER.debug("bind with bindDN:" + bindDN + " " + "bindPassword=" + bindPassword.replaceAll(".", "*"));
        trace.add("Preparing to bind to the LDAP server with DN = " + bindDN + " and password '****");
    } else {
        LOGGER.debug("bind anonymous");
        trace.add("Preparing to bind anonymously to the LDAP server");
    }
    try {
        return new InitialLdapContext(env, null);
    } catch (NamingException e) {
        for (String msg : trace) {
            LOGGER.error(msg);
        }
        LOGGER.error("Getting the initial ldap context failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        try {
            new InitialDirContext(env);
        } catch (NamingException e1) {
            LOGGER.error("Getting the initial dir context failed with " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
        return null;
    }
}

From source file:org.jboss.as.test.integration.security.loginmodules.RemotingLoginModuleTestCase.java

/**
 * Configure {@link SSLContext} and create EJB client properties.
 *
 * @param clientName/*from w  ww  . jav  a  2  s  .co m*/
 * @return
 * @throws Exception
 */
private Properties configureEjbClient(String clientName) throws Exception {
    // create new SSLContext based on client keystore and truststore and use this SSLContext instance as a default for this test
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(
            KeyStoreUtil.getKeyStore(getClientKeystoreFile(clientName), KEYSTORE_PASSWORD.toCharArray()),
            KEYSTORE_PASSWORD.toCharArray());

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory
            .init(KeyStoreUtil.getKeyStore(CLIENTS_TRUSTSTORE_FILE, KEYSTORE_PASSWORD.toCharArray()));

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    SSLContext.setDefault(sslContext);

    final Properties env = new Properties();
    env.put("java.naming.factory.initial", "org.jboss.naming.remote.client.InitialContextFactory");
    env.put("java.naming.provider.url", "remote://" + mgmtClient.getMgmtAddress() + ":" + REMOTING_PORT_TEST);
    env.put("jboss.naming.client.ejb.context", "true");
    env.put("jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT", "false");
    env.put(Context.SECURITY_PRINCIPAL, "admin");
    env.put(Context.SECURITY_CREDENTIALS, "testing");

    // SSL related config parameters
    env.put("jboss.naming.client.remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED",
            "true");
    env.put("jboss.naming.client.connect.options.org.xnio.Options.SSL_STARTTLS", "true");
    return env;
}

From source file:org.apache.directory.server.ldap.handlers.sasl.AbstractSaslCallbackHandler.java

/**
 * Convenience method for getting an environment suitable for acquiring
 * an {@link LdapContext} for the client.
 * // ww w. j ava  2 s  .  c  o m
 * @param session The current session.
 * @return An environment suitable for acquiring an {@link LdapContext} for the client.
 */
protected Hashtable<String, Object> getEnvironment(IoSession session) {
    Hashtable<String, Object> env = new Hashtable<>();
    env.put(Context.PROVIDER_URL, session.getAttribute("baseDn"));
    env.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.directory.server.core.jndi.CoreContextFactory");
    env.put(Context.SECURITY_PRINCIPAL, ServerDNConstants.ADMIN_SYSTEM_DN);
    env.put(Context.SECURITY_CREDENTIALS, "secret");
    env.put(Context.SECURITY_AUTHENTICATION, AuthenticationLevel.SIMPLE.toString());

    return env;
}

From source file:org.apache.hadoop.security.authentication.server.LdapAuthenticationHandler.java

private void authenticateWithoutTlsExtension(String userDN, String password) throws AuthenticationException {
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, providerUrl);
    env.put(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION);
    env.put(Context.SECURITY_PRINCIPAL, userDN);
    env.put(Context.SECURITY_CREDENTIALS, password);

    try {//w w  w.  ja v a2 s .  c  om
        // Create initial context
        Context ctx = new InitialDirContext(env);
        ctx.close();
        logger.debug("Authentication successful for {}", userDN);

    } catch (NamingException e) {
        throw new AuthenticationException("Error validating LDAP user", e);
    }
}

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

/**
 * Returns <i>true</i> if the Active Directory account and password are
 * valid (e.g. a context can be successfully established) or <i>false</i>
 * otherwise./*from w  ww.ja  va2s.c  om*/
 *
 * @param anAccountName An Active Directory account name.
 * @param anAccountPassword An Active Directory account passowrd.
 *
 * @return <i>true</i> or <i>false</i>
 */
@SuppressWarnings("unchecked")
public boolean isAccountValid(String anAccountName, String anAccountPassword) {
    boolean isValid = false;
    Logger appLogger = mAppMgr.getLogger(this, "isAccountValid");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    DataBag userBag = schemaUserBag();
    userBag.setValueByName(LDAP_ACCOUNT_NAME, anAccountName);

    try {
        loadUserByAccountName(userBag);
        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,
                userBag.getValueAsString(LDAP_DISTINGUISHED_NAME));
        environmentalVariables.put(Context.SECURITY_CREDENTIALS, anAccountPassword);
        environmentalVariables.put(Context.REFERRAL, getPropertyValue("referral_handling", "ignore"));
        environmentalVariables.put(Context.SECURITY_AUTHENTICATION,
                getPropertyValue("authentication", "simple"));

        LdapContext ldapContext = new InitialLdapContext(environmentalVariables, null);
        ldapContext.close();

        isValid = true;
    } catch (Exception ignored) {
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);

    return isValid;
}

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

/**
 * //from w ww.ja  v a2  s.co  m
 * Connect to LDAP with the User-Name and Password given as parameters
 * 
 * Configuration: LDAP URL = ldapContext.xml (property=ldapURL) LDAP Base =
 * ldapContext.xml (property=ldapBase) LDAP Attributes Map =
 * ldapContext.xml (property=userAttrs)
 * 
 * 
 * @param uid The users LDAP login name (can't be null)
 * @param pwd The users LDAP password (can't be null)
 * 
 * @return After successful bind Attributes otherwise NULL
 * 
 * @throws NamingException
 */
@Override
public Attributes bindUser(String uid, String pwd, LDAPError errors) {
    // get user name, password and attributes
    String ldapUrl = ldapLoginModule.getLdapUrl();
    String[] userAttr = syncConfiguration.getUserAttributes();

    if (uid == null || pwd == null) {
        if (log.isDebug())
            log.debug("Error when trying to bind user, missing username or password. Username::" + uid
                    + " pwd::" + pwd);
        errors.insert("Username and password must be selected");
        return null;
    }

    LdapContext ctx = bindSystem();
    if (ctx == null) {
        errors.insert("LDAP connection error");
        return null;
    }
    String userDN = ldapDao.searchUserDN(uid, ctx);
    if (userDN == null) {
        log.info("Error when trying to bind user with username::" + uid + " - user not found on LDAP server"
                + (ldapLoginModule.isCacheLDAPPwdAsOLATPwdOnLogin() ? ", trying with OLAT login provider"
                        : ""));
        errors.insert("Username or password incorrect");
        return null;
    }

    // Ok, so far so good, user exists. Now try to fetch attributes using the
    // users credentials
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapUrl);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, userDN);
    env.put(Context.SECURITY_CREDENTIALS, pwd);
    if (ldapLoginModule.getLdapConnectionTimeout() != null) {
        env.put(TIMEOUT_KEY, ldapLoginModule.getLdapConnectionTimeout().toString());
    }
    if (ldapLoginModule.isSslEnabled()) {
        enableSSL(env);
    }

    try {
        Control[] connectCtls = new Control[] {};
        LdapContext userBind = new InitialLdapContext(env, connectCtls);
        Attributes attributes = userBind.getAttributes(userDN, userAttr);
        userBind.close();
        return attributes;
    } catch (AuthenticationException e) {
        log.info("Error when trying to bind user with username::" + uid + " - invalid LDAP password");
        errors.insert("Username or password incorrect");
        return null;
    } catch (NamingException e) {
        log.error("NamingException when trying to get attributes after binding user with username::" + uid, e);
        errors.insert("Username or password incorrect");
        return null;
    }
}

From source file:org.apache.synapse.transport.jms.JMSConnectionFactory.java

/**
 * Begin [or restart] listening for messages on the list of destinations associated
 * with this connection factory. (Called during Axis2 initialization of
 * the Transport receivers, or after a disconnection has been detected)
 *
 * When called from the JMS transport sender, this call simply acquires the actual
 * JMS connection factory from the JNDI, creates a new connection and starts it.
 *
 * @throws JMSException on exceptions// w  ww.  java2  s .co  m
 * @throws NamingException on exceptions
 */
public synchronized void connectAndListen() throws JMSException, NamingException {

    // if this is a reconnection/re-initialization effort after the detection of a
    // disconnection, close all sessions and the CF connection and re-initialize
    if (connection != null) {
        log.info("Re-initializing the JMS connection factory : " + name);

        Iterator sessionIter = jmsSessions.values().iterator();
        while (sessionIter.hasNext()) {
            try {
                ((Session) sessionIter.next()).close();
            } catch (JMSException ignore) {
            }
        }
        try {
            connection.stop();
        } catch (JMSException ignore) {
        }

    } else {
        if (log.isDebugEnabled()) {
            log.debug("Initializing the JMS connection factory : " + name);
        }
    }

    // get the CF reference freshly [again] from JNDI
    context = new InitialContext(jndiProperties);
    conFactory = (ConnectionFactory) context.lookup(connFactoryJNDIName);
    log.info("Connected to the JMS connection factory : " + connFactoryJNDIName);

    try {
        ConnectionFactory conFac = null;
        QueueConnectionFactory qConFac = null;
        TopicConnectionFactory tConFac = null;
        if (JMSConstants.DESTINATION_TYPE_QUEUE.equals(getConnectionFactoryType())) {
            qConFac = (QueueConnectionFactory) conFactory;
        } else if (JMSConstants.DESTINATION_TYPE_TOPIC.equals(getConnectionFactoryType())) {
            tConFac = (TopicConnectionFactory) conFactory;
        } else {
            handleException("Unable to determine type of Connection Factory - i.e. Queue/Topic", null);
        }

        String user = (String) jndiProperties.get(Context.SECURITY_PRINCIPAL);
        String pass = (String) jndiProperties.get(Context.SECURITY_CREDENTIALS);

        if (user != null && pass != null) {
            if (qConFac != null) {
                connection = qConFac.createQueueConnection(user, pass);
            } else if (tConFac != null) {
                connection = tConFac.createTopicConnection(user, pass);
            }
        } else {
            if (qConFac != null) {
                connection = qConFac.createQueueConnection();
            } else if (tConFac != null) {
                connection = tConFac.createTopicConnection();
            }
        }

        connection.setExceptionListener(this);

    } catch (JMSException e) {
        handleException("Error connecting to Connection Factory : " + connFactoryJNDIName, e);
    }

    Iterator destJNDINameIter = serviceJNDINameMapping.keySet().iterator();
    while (destJNDINameIter.hasNext()) {
        String destJNDIName = (String) destJNDINameIter.next();
        String destinationType = (String) destinationTypeMapping.get(destJNDIName);
        startListeningOnDestination(destJNDIName, destinationType);
    }

    connection.start(); // indicate readyness to start receiving messages
    log.info("Connection factory : " + name + " initialized...");
}