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:com.mirth.connect.connectors.jms.JmsReceiverTests.java

private static ConnectionFactory lookupConnectionFactoryWithJndi(JmsConnectorProperties connectorProperties)
        throws Exception {
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.PROVIDER_URL, connectorProperties.getJndiProviderUrl());
    env.put(Context.INITIAL_CONTEXT_FACTORY, connectorProperties.getJndiInitialContextFactory());
    env.put(Context.SECURITY_PRINCIPAL, connectorProperties.getUsername());
    env.put(Context.SECURITY_CREDENTIALS, connectorProperties.getPassword());

    initialContext = new InitialContext(env);
    String connectionFactoryName = connectorProperties.getJndiConnectionFactoryName();
    return (ConnectionFactory) initialContext.lookup(connectionFactoryName);
}

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

public static boolean authenticate(TSiteBean siteBean, String loginName, String ppassword)
        throws NamingException {
    boolean userIsOK = false;
    ArrayList<String> trace = new ArrayList<String>();

    trace.add("Ldap trying to authenticate user with loginname >" + loginName + "<");

    if (siteBean.getLdapServerURL().startsWith("ldaps:")) {
        System.setProperty("javax.net.ssl.trustStore", PATH_TO_KEY_STORE);
    }//from w  w w . j  a v a 2s . com
    // get the CN
    String keyDn = getCn(siteBean, loginName);

    try {
        if (keyDn != null) {
            trace.add("Using keyDn >" + keyDn + "<");
            // Set up the environment for creating the initial context
            Hashtable<String, String> env = new Hashtable<String, String>(11);
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.PROVIDER_URL, siteBean.getLdapServerURL());
            env.put(Context.SECURITY_AUTHENTICATION, "simple");
            env.put(Context.SECURITY_PRINCIPAL, keyDn);
            env.put(Context.SECURITY_CREDENTIALS, ppassword);
            // Create initial context
            DirContext itest = new InitialDirContext(env);
            itest.close();
            // user was validated
            userIsOK = true;
        }
        return userIsOK;
    } catch (NamingException e) {
        for (String msg : trace) {
            LOGGER.warn(msg);
        }
        throw e;
    }
}

From source file:ldap.SearchUtility.java

/**
 * open the directory connection./*from  w w w. j a v a  2 s.c  o  m*/
 *
 * @param url
 * @param tracing
 * @return
 * @throws javax.naming.NamingException
 */
private DirContext setupJNDIConnection(String url, String userDN, String password, boolean tracing)
        throws NamingException {
    /*
    * First, set up a large number of environment variables to sensible default valuse
    */

    Hashtable env = new Hashtable();
    // sanity check
    if (url == null)
        throw new NamingException("URL not specified in openContext()!");

    // set the tracing level now, since it can't be set once the connection is open.
    if (tracing)
        env.put("com.sun.jndi.ldap.trace.ber", System.err); // echo trace to standard error output

    env.put("java.naming.ldap.version", "3"); // always use ldap v3 - v2 too limited
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // use default jndi provider
    env.put("java.naming.ldap.deleteRDN", "false"); // usually what we want
    env.put(Context.REFERRAL, "ignore"); //could be: follow, ignore, throw
    env.put("java.naming.ldap.derefAliases", "finding"); // could be: finding, searching, etc.
    env.put(Context.SECURITY_AUTHENTICATION, "simple"); // 'simple' = username + password
    env.put(Context.SECURITY_PRINCIPAL, userDN); // add the full user dn
    env.put(Context.SECURITY_CREDENTIALS, password); // stupid jndi requires us to cast this to a string-
    env.put(Context.PROVIDER_URL, url); // the ldap url to connect to; e.g. "ldap://ca.com:389"

    /*
    *  Open the actual LDAP session using the above environment variables
    */

    DirContext newContext = new InitialDirContext(env);

    if (newContext == null)
        throw new NamingException(
                "Internal Error with jndi connection: No Context was returned, however no exception was reported by jndi.");

    return newContext;

}

From source file:org.jkcsoft.java.util.JndiHelper.java

public static DirContext getDirContext(BehavioralContext bctx, Object principal, Object credentials)
        throws NamingException {
    DirContext ctx = null;/*from w ww .  j  a  v  a 2  s  .c  o  m*/

    Configuration tconfig = bctx.getConfig();
    String ldapProvider = "ldap" + "://" + tconfig.getString(Constants.KEY_AD_HOST) + ":"
            + tconfig.getString(Constants.KEY_AD_PORT) + "/" + tconfig.getString(Constants.KEY_AD_ROOT_DN);

    log.info("Using LDAP url: [" + ldapProvider + "]");

    //        String url, String contextFactoryName,

    Hashtable jndiEnv = new Hashtable();

    jndiEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    jndiEnv.put(Context.PROVIDER_URL, ldapProvider);
    jndiEnv.put(Context.REFERRAL, "follow");

    if (tconfig.getBoolean(Constants.KEY_AD_SSL)) {
        log.info("Using SSL for LDAP");
        jndiEnv.put(Context.SECURITY_PROTOCOL, "ssl");
    }
    jndiEnv.put(Context.SECURITY_AUTHENTICATION, "simple");

    if (principal != null)
        jndiEnv.put(Context.SECURITY_PRINCIPAL, principal);

    if (credentials != null)
        jndiEnv.put(Context.SECURITY_CREDENTIALS, credentials);

    try {
        // Creating the JNDI directory context (with LDAP context
        // factory), performs an LDAP bind to the LDAP provider thereby
        // authenticating the username/pw.
        ctx = new InitialDirContext(jndiEnv);
    } catch (NamingException ex) {
        log.error("Directory context init failed", ex);
        throw ex;
    }

    return ctx;
}

From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java

protected boolean userExists(String id) {
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_CREDENTIALS, "secret");

    try {/*from  w w w  .  j a  v a2s . co  m*/
        DirContext ctx = new InitialDirContext(env);

        /*
         * Setup subtree scope to tell LDAP to recursively descend directory structure during searches.
         */
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        /*
         * Setup the directory entry attributes we want to search for. In this case it is the user's ID.
         */

        String filter = "(&(objectclass=person)(uid=" + escapeSearchFilterTerm(id) + "))";

        /* Execute the search, starting at the directory level of Users */

        NamingEnumeration hits = ctx.search(getBasePath(), filter, searchControls);

        /* All we need to know is if there were any hits at all. */

        if (hits.hasMore()) {
            hits.close();
            ctx.close();
            return true;
        } else {
            hits.close();
            ctx.close();
            return false;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:org.acegisecurity.ldap.DefaultInitialDirContextFactory.java

private InitialDirContext connect(Hashtable env) {
    if (logger.isDebugEnabled()) {
        Hashtable envClone = (Hashtable) env.clone();

        if (envClone.containsKey(Context.SECURITY_CREDENTIALS)) {
            envClone.put(Context.SECURITY_CREDENTIALS, "******");
        }//w  w  w .  j  a va  2s. c om

        logger.debug("Creating InitialDirContext with environment " + envClone);
    }

    try {
        return useLdapContext ? new InitialLdapContext(env, null) : new InitialDirContext(env);
    } catch (NamingException ne) {
        if ((ne instanceof javax.naming.AuthenticationException)
                || (ne instanceof OperationNotSupportedException)) {
            throw new BadCredentialsException(
                    messages.getMessage("DefaultIntitalDirContextFactory.badCredentials", "Bad credentials"),
                    ne);
        }

        if (ne instanceof CommunicationException) {
            throw new LdapDataAccessException(
                    messages.getMessage("DefaultIntitalDirContextFactory.communicationFailure",
                            "Unable to connect to LDAP server"),
                    ne);
        }

        throw new LdapDataAccessException(
                messages.getMessage("DefaultIntitalDirContextFactory.unexpectedException",
                        "Failed to obtain InitialDirContext due to unexpected exception"),
                ne);
    }
}

From source file:org.exoplatform.services.organization.DummyLDAPServiceImpl.java

public boolean authenticate(String userDN, String password) throws NamingException {
    Hashtable<String, Object> props = new Hashtable<String, Object>(env);
    props.put(Context.SECURITY_AUTHENTICATION, "simple");
    props.put(Context.SECURITY_PRINCIPAL, userDN);
    props.put(Context.SECURITY_CREDENTIALS, password);
    props.put("com.sun.jndi.ldap.connect.pool", "false");

    InitialContext ctx = null;/*from w  w w  .  jav  a 2s .c o  m*/
    try {
        ctx = new DummyLdapContext(new InitialLdapContext(props, null));
        return true;
    } catch (NamingException e) {
        LOG.debug("Error during initialization LDAP Context", e);
        return false;
    } finally {
        closeContext(ctx);
    }
}

From source file:LDAPTest.java

/**
     * Gets a context from the properties specified in the file ldapserver.properties
     * @return the directory context//from ww w.  j  a va2 s  .co m
     */
    public static DirContext getContext() throws NamingException, IOException {
        Properties props = new Properties();
        FileInputStream in = new FileInputStream("ldapserver.properties");
        props.load(in);
        in.close();

        String url = props.getProperty("ldap.url");
        String username = props.getProperty("ldap.username");
        String password = props.getProperty("ldap.password");

        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.SECURITY_PRINCIPAL, username);
        env.put(Context.SECURITY_CREDENTIALS, password);
        DirContext initial = new InitialDirContext(env);
        DirContext context = (DirContext) initial.lookup(url);

        return context;
    }

From source file:com.predic8.membrane.core.interceptor.authentication.session.LDAPUserDataProvider.java

/**
 * @throws NoSuchElementException if no user could be found with the given login
 * @throws AuthenticationException if the password does not match
 * @throws CommunicationException e.g. on server timeout
 * @throws NamingException on any other LDAP error
 *//*w w w. j a va 2 s  .co m*/
private HashMap<String, String> auth(String login, String password) throws NamingException {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, url);
    env.put("com.sun.jndi.ldap.read.timeout", timeout);
    env.put("com.sun.jndi.ldap.connect.timeout", connectTimeout);
    if (binddn != null) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, binddn);
        env.put(Context.SECURITY_CREDENTIALS, bindpw);
    }

    HashMap<String, String> userAttrs = new HashMap<String, String>();
    String uid;

    DirContext ctx = new InitialDirContext(env);
    try {
        uid = searchUser(login, userAttrs, ctx);
    } finally {
        ctx.close();
    }

    if (passwordAttribute != null) {
        if (!userAttrs.containsKey("_pass"))
            throw new NoSuchElementException();
        String pass = userAttrs.get("_pass");
        if (pass == null || !pass.startsWith("{x-plain}"))
            throw new NoSuchElementException();
        log.debug("found password");
        pass = pass.substring(9);
        if (!pass.equals(password))
            throw new NoSuchElementException();
        userAttrs.remove("_pass");
    } else {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, uid + "," + base);
        env.put(Context.SECURITY_CREDENTIALS, password);
        DirContext ctx2 = new InitialDirContext(env);
        try {
            if (readAttributesAsSelf)
                searchUser(login, userAttrs, ctx2);
        } finally {
            ctx2.close();
        }
    }
    return userAttrs;
}

From source file:xc.mst.manager.user.DefaultUserService.java

/**
 * Creates a connection to the LDAP server based on values defined in the configuration file.
 * This method logs into the server with a specified username and password
 * /*from w  w  w .jav  a  2  s. co  m*/
 * @param username
 *            The username to log into the LDAP server
 * @param password
 *            The password to log into the LDAP server
 * @return A connection to the LDAP server defined in the configuration file.
 * @throws ILSException
 *             if the username and password were wrong or we couldn't find the LDAP server
 */
private static DirContext getLDAPConnection(String username, String password, Server loginserver) {

    Properties ldapProperties = getGenericLDAPProperties(loginserver);
    try {
        // Set up the environment for creating the initial context

        // Get the username attribute and start location on the LDAP server from the configuration file
        String usernameAttribute = loginserver.getUserNameAttribute();
        String startLocation = loginserver.getStartLocation();

        // Set up the properties to authenticate with the correct username and password
        // The username passed to this function will be something like "jsmith", but we
        // need to authenticate to the correct LDAP location using the provided parameter.
        // For this reason we pull the username attribute at start locations from the
        // configuration file. The result will be setting the SECURITY_PRINCIPAL (LDAP username)
        // to something like "uid=jsmith, ou=people, dc=rochester, dc=edu"
        ldapProperties.setProperty(Context.SECURITY_AUTHENTICATION, "simple"); // Set this property because we will be authenticating
        ldapProperties.setProperty(Context.SECURITY_PRINCIPAL,
                usernameAttribute + "=" + username + ", " + startLocation);
        ldapProperties.setProperty(Context.SECURITY_CREDENTIALS, password);

        // Get the environment properties (props) for creating initial
        // context and specifying LDAP service provider parameters.
        return new InitialDirContext(ldapProperties);
    }
    // catch(MalformedURLException e1) {} // not thrown in above, but I thought I saw this in the log with misconfigured ldap?
    // catch(AuthenticationException e2) {} // more specific then below, I think this is the one thrown if invalid password.
    catch (NamingException e) {
        // If the exception was an error code 49, the username or password was incorrect.
        log.error(
                "Exception occured while authenticating user against LDAP server.If the exception was an error code 49, the username or password was incorrect",
                e);
        InitialDirContext in = null;
        return in;
    }
}