Example usage for javax.naming.directory InitialDirContext InitialDirContext

List of usage examples for javax.naming.directory InitialDirContext InitialDirContext

Introduction

In this page you can find the example usage for javax.naming.directory InitialDirContext InitialDirContext.

Prototype

public InitialDirContext(Hashtable<?, ?> environment) throws NamingException 

Source Link

Document

Constructs an initial DirContext using the supplied environment.

Usage

From source file:LDAPTest.java

/**
     * Gets a context from the properties specified in the file ldapserver.properties
     * @return the directory context/*  w  w w . j a  va2s  .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:org.jkcsoft.java.util.JndiHelper.java

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

    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:ldap.SearchUtility.java

/**
 * open the directory connection./*w  ww . ja v  a 2 s.c om*/
 *
 * @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: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  .c  o 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: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, "******");
        }//from  ww w  .java 2 s  .  com

        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: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  2s.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;
    }
}

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

/**
 * Resets the password for the given user.
 *
 * @param username the username/*from   ww  w.j  a va  2  s.c o  m*/
 * @param password the new password
 * @throws PortalServiceException for any errors encountered
 */
public void resetPassword(String username, String password) throws PortalServiceException {
    DirContext ctx = null;
    try {
        ctx = new InitialDirContext(env);
        BasicAttribute pw = new BasicAttribute("userPassword", hash(password));

        ModificationItem[] mods = new ModificationItem[1];
        mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, pw);
        ctx.modifyAttributes(MessageFormat.format(userDNPattern, username), mods);
    } catch (NamingException e) {
        throw new PortalServiceConfigurationException("Unable to reset password.", e);
    } finally {
        closeContext(ctx);
    }
}

From source file:org.webterm.core.plugin.authentication.LdapAuthentication.java

@Override
public void init() {
    LOG.info("Initializing LDAP authentication..."); //$NON-NLS-1$

    try {/*from ww w .j  a  va2 s  .c om*/
        final ConfigurationReader config = ConfigurationReader.getInstance();
        final String serverName = config.getApplicationProperty(CONFIG_SERVER_NAME);
        final String serverPort = config.getApplicationProperty(CONFIG_SERVER_PORT);
        final String bindDn = config.getApplicationProperty(CONFIG_BIND_DN);
        final String bindPwd = config.getApplicationProperty(CONFIG_BIND_PWD);
        this.baseDn = config.getApplicationProperty(CONFIG_BASE_DN);
        this.attrUser = config.getApplicationProperty(CONFIG_ATTR_USER);
        this.attrPwd = config.getApplicationProperty(CONFIG_ATTR_PWD);
        this.checkMethode = this.map.get(config.getApplicationProperty(CONFIG_PASSWORD_ENCODE));
        if (this.checkMethode == null) {
            LOG.fatal("unknown method: " + config.getApplicationProperty(CONFIG_PASSWORD_ENCODE)); //$NON-NLS-1$
        }

        final Hashtable<String, String> ldapEnv = new Hashtable<String, String>(); // NOPMD - HashTable is needed
        ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); //$NON-NLS-1$
        ldapEnv.put(Context.PROVIDER_URL, "ldap://" + serverName + ":" + serverPort); //$NON-NLS-1$ //$NON-NLS-2$
        ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");//$NON-NLS-1$
        ldapEnv.put(Context.SECURITY_PRINCIPAL, bindDn);
        ldapEnv.put(Context.SECURITY_CREDENTIALS, bindPwd);
        this.ldapContext = new InitialDirContext(ldapEnv);
    } catch (Exception ex) {
        LOG.error(ex, ex);
    }
}

From source file:com.evolveum.midpoint.pwdfilter.opendj.PasswordPusher.java

private void readConfig() throws InitializationException {

    String configFile = "/opt/midpoint/opendj-pwdpusher.xml";
    if (System.getProperty("config") != null) {
        configFile = System.getProperty("config");
    }//from   ww  w .  j av  a2  s . c o m

    File f = new File(configFile);
    if (!f.exists() || !f.canRead()) {
        throw new IllegalArgumentException("Config file " + configFile + " does not exist or is not readable");
    }

    try {
        XMLConfiguration config = new XMLConfiguration(f);

        String notifierDN = "cn=" + config.getString("passwordpusher.statusNotifierName")
                + ",cn=Account Status Notification Handlers";
        String ldapURL = config.getString("passwordpusher.ldapServerURL");
        boolean ldapSSL = config.getBoolean("passwordpusher.ldapServerSSL");
        String ldapUsername = config.getString("passwordpusher.ldapServerUsername");
        String ldapPassword = config.getString("passwordpusher.ldapServerPassword");

        Hashtable<Object, Object> env = new Hashtable<Object, Object>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ldapURL + "/cn=config");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, ldapUsername);
        env.put(Context.SECURITY_CREDENTIALS, ldapPassword);

        if (ldapSSL) {
            env.put(Context.SECURITY_PROTOCOL, "ssl");
        }

        try {
            DirContext context = new InitialDirContext(env);
            Attributes attr = context.getAttributes(notifierDN);

            this.endPoint = attr.get("ds-cfg-referrals-url").get(0).toString();
            this.username = attr.get("ds-cfg-midpoint-username").get(0).toString();
            this.password = attr.get("ds-cfg-midpoint-password").get(0).toString();
            this.pwdChangeDirectory = attr.get("ds-cfg-midpoint-passwordcachedir").get(0).toString();
        } catch (NamingException ne) {
            throw new InitializationException(
                    ERR_MIDPOINT_PWDSYNC_READING_CONFIG_FROM_LDAP.get(ne.getMessage()), ne);
        }
    } catch (ConfigurationException ce) {
        throw new InitializationException(ERR_MIDPOINT_PWDSYNC_PARSING_XML_CONFIG.get(ce.getMessage()), ce);
    }
}

From source file:py.una.pol.karaku.security.KarakuUserService.java

private InitialDirContext getInitialDirContext(String user, String pass) throws NamingException {

    Map<Object, String> env = new HashMap<Object, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, getServerLocation());

    env.put(Context.SECURITY_PRINCIPAL, user);
    env.put(Context.SECURITY_CREDENTIALS, pass);
    return new InitialDirContext(new Hashtable<Object, String>(env));
}