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:org.infoscoop.account.ldap.LDAPAccountManager.java

public void login(String userid, String password) throws AuthenticationException {
    try {/* w  w w  .j  av  a2  s .  com*/
        LDAPAccount user = (LDAPAccount) getUser(userid);
        if (user == null) {
            throw new AuthenticationException(userid + " is not found.");
        }
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, this.connectionURL);
        env.put("java.naming.ldap.version", "3");
        env.put(Context.SECURITY_PRINCIPAL, user.getDn());
        env.put(Context.SECURITY_CREDENTIALS, password);

        new InitialDirContext(env);

    } catch (NamingException e) {
        throw new AuthenticationException(e);
    }
}

From source file:ldap.LdapApi.java

/**
 * open the directory connection./*from   ww  w .  jav a 2  s . com*/
 * @param url
 * @param dn
 * @param password
 * @param tracing
 * @return DirContext - context
 * @throws NamingException
 */
private DirContext setupJNDIConnection(String url, String userDN, String password, boolean tracing)
        throws NamingException {
    /*
    *  setup  environment variables to sensible default valuse
    */
    Hashtable env = new Hashtable();
    // sanity check
    if (url == null) {
        throw new LdapException("URL not specified in openContext()!");
    }

    // tracing on/off, 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(LdapConstants.ldapVersionStr, LdapConstants.ldapVersion); // always use ldap v3 - v2 too limited
    env.put(Context.INITIAL_CONTEXT_FACTORY, LdapConstants.ldapContext); // use default jndi provider
    env.put(LdapConstants.ldapDeleteRdn, LdapConstants.ldapDeleteRdnValue); // usually what we want
    //env.put(Context.REFERRAL, "ignore");                    //could be: follow, ignore, throw
    env.put(Context.REFERRAL, LdapConstants.ldapIgnore); //could be: follow, ignore, throw
    // env.put("java.naming.ldap.derefAliases", "finding");    // could be: finding, searching, etc.
    env.put(LdapConstants.ldapFindingAliases, LdapConstants.ldapFindingStr); // could be: finding, searching, etc.

    //env.put(Context.SECURITY_AUTHENTICATION, "simple");         // 'simple' = username + password
    env.put(Context.SECURITY_AUTHENTICATION, LdapConstants.ldapSecurityAuth); // '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
     */
    context = new InitialDirContext(env);
    if (context == null) {
        throw new NamingException(
                "Internal Error with jndi connection: No Context was returned, however no exception was reported by jndi.");
    } else {
        logger.info("context is not null");
    }
    return context;
}

From source file:org.apache.directory.server.operations.bind.MiscBindIT.java

/**
 * Reproduces the problem with/* w  w w .  j a va  2s  . c o  m*/
 * <a href="http://issues.apache.org/jira/browse/DIREVE-239">DIREVE-239</a>.
 *
 * @throws Exception if anything goes wrong
 */
@Test
public void testAdminAccessBug() throws Exception {
    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

    // Use the SUN JNDI provider to hit server port and bind as anonymous

    final Hashtable<String, Object> env = new Hashtable<String, Object>();

    env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()));
    env.put("java.naming.ldap.version", "3");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    Attributes attributes = new BasicAttributes(true);
    Attribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("top");
    objectClass.add("organizationalUnit");
    attributes.put(objectClass);
    attributes.put("ou", "blah");
    InitialDirContext ctx = new InitialDirContext(env);
    ctx.createSubcontext("ou=blah,ou=system", attributes);
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.OBJECT_SCOPE);
    controls.setReturningAttributes(new String[] { "+" });
    NamingEnumeration<SearchResult> list = ctx.search("ou=blah,ou=system", "(objectClass=*)", controls);
    SearchResult result = list.next();
    list.close();
    Attribute creatorsName = result.getAttributes().get("creatorsName");
    assertEquals("", creatorsName.get());
    ctx.destroySubcontext("ou=blah,ou=system");
}

From source file:org.kitodo.services.data.LdapServerService.java

/**
 * Check if connection with login and password possible.
 *
 * @param user//from  w  w  w .  ja v  a  2s  . co m
 *            User object
 * @param password
 *            String
 * @return Login correct or not
 */
public boolean isUserPasswordCorrect(User user, String password) {
    logger.debug("start login session with ldap");
    Hashtable<String, String> env = initializeWithLdapConnectionSettings(user.getLdapGroup().getLdapServer());

    // Start TLS
    if (ConfigCore.getBooleanParameter(Parameters.LDAP_USE_TLS)) {
        logger.debug("use TLS for auth");
        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, buildUserDN(user));
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
            ctx.reconnect(null);
            return true;
            // Perform search for privileged attributes under authenticated
            // context

        } catch (IOException e) {
            logger.error("TLS negotiation error:", e);
            return false;
        } catch (NamingException e) {
            logger.error("JNDI error:", e);
            return false;
        } finally {
            if (tls != null) {
                try {
                    // Tear down TLS connection
                    tls.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (ctx != null) {
                try {
                    // Close LDAP connection
                    ctx.close();
                } catch (NamingException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    } else {
        logger.debug("don't use TLS for auth");
        if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) {
            env.put(Context.SECURITY_AUTHENTICATION, "none");
            // TODO auf passwort testen
        } else {
            env.put(Context.SECURITY_PRINCIPAL, buildUserDN(user));
            env.put(Context.SECURITY_CREDENTIALS, password);
        }
        logger.debug("ldap environment set");

        try {
            logger.debug("start classic ldap authentication");
            logger.debug("user DN is {}", buildUserDN(user));

            if (ConfigCore.getParameter(Parameters.LDAP_ATTRIBUTE_TO_TEST) == null) {
                logger.debug("ldap attribute to test is null");
                DirContext ctx = new InitialDirContext(env);
                ctx.close();
                return true;
            } else {
                logger.debug("ldap attribute to test is not null");
                DirContext ctx = new InitialDirContext(env);

                Attributes attrs = ctx.getAttributes(buildUserDN(user));
                Attribute la = attrs.get(ConfigCore.getParameter(Parameters.LDAP_ATTRIBUTE_TO_TEST));
                logger.debug("ldap attributes set");
                String test = (String) la.get(0);
                if (test.equals(ConfigCore.getParameter(Parameters.LDAP_VALUE_OF_ATTRIBUTE))) {
                    logger.debug("ldap ok");
                    ctx.close();
                    return true;
                } else {
                    logger.debug("ldap not ok");
                    ctx.close();
                    return false;
                }
            }
        } catch (NamingException e) {
            logger.debug("login not allowed for {}. Exception: {}", user.getLogin(), e);
            return false;
        }
    }
}

From source file:org.apache.nifi.processors.enrich.QueryDNS.java

protected void initializeContext(Hashtable<String, String> env) throws NamingException {
    this.ictx = new InitialDirContext(env);
    this.initialized = new AtomicBoolean(false);
    initialized.set(true);/*ww  w.  j a va  2s  . co m*/
}

From source file:org.kitodo.production.services.data.LdapServerService.java

/**
 * Check if User already exists on system.
 *
 * @param user//from   w w w  .j a v  a2  s  .  c  o m
 *            The User.
 * @return result as boolean
 */
public boolean isUserAlreadyExists(User user) {
    Hashtable<String, String> ldapEnvironment = initializeWithLdapConnectionSettings(
            user.getLdapGroup().getLdapServer());
    DirContext ctx;
    boolean result = false;
    try {
        ctx = new InitialDirContext(ldapEnvironment);
        Attributes matchAttrs = new BasicAttributes(true);
        NamingEnumeration<SearchResult> answer = ctx.search(buildUserDN(user), matchAttrs);
        result = answer.hasMoreElements();

        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            logger.debug(">>>{}", sr.getName());
            Attributes attrs = sr.getAttributes();
            String givenName = getStringForAttribute(attrs, "givenName");
            String surName = getStringForAttribute(attrs, "sn");
            String mail = getStringForAttribute(attrs, "mail");
            String cn = getStringForAttribute(attrs, "cn");
            String homeDirectory = getStringForAttribute(attrs, "homeDirectory");

            logger.debug(givenName);
            logger.debug(surName);
            logger.debug(mail);
            logger.debug(cn);
            logger.debug(homeDirectory);
        }

        ctx.close();
    } catch (NamingException e) {
        logger.error(e.getMessage(), e);
    }
    return result;
}

From source file:org.apache.directory.server.tools.commands.exportcmd.ExportCommandExecutor.java

/**
 * Gets and returns the entries from the server.
 * /* w  ww. j  av  a 2s  .c  o m*/
 * @throws ToolCommandException
 * @throws NamingException
 */
public NamingEnumeration connectToServerAndGetEntries() throws ToolCommandException {
    // Connecting to the LDAP Server
    if (isDebugEnabled()) {
        notifyOutputListener("Connecting to LDAP server");
        notifyOutputListener("Host: " + host);
        notifyOutputListener("Port: " + port);
        notifyOutputListener("User DN: " + user);
        notifyOutputListener("Base DN: " + baseDN);
        notifyOutputListener("Authentication: " + auth);
    }
    Hashtable env = new Hashtable();
    env.put(Context.SECURITY_PRINCIPAL, user);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.SECURITY_AUTHENTICATION, auth);
    env.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port + "/" + baseDN);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    DirContext ctx;
    try {
        ctx = new InitialDirContext(env);
    } catch (NamingException e) {
        throw new ToolCommandException("Could not connect to the server.\nError: " + e.getMessage());
    }

    // Setting up search scope
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(scope);

    // Fetching entries
    try {
        return ctx.search(exportPoint, "(objectClass=*)", ctls);
    } catch (NamingException e) {
        throw new ToolCommandException("Could not retreive entries");
    }
}

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   w  w  w .j  a  va  2 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:gov.medicaid.dao.impl.LDAPIdentityProviderDAOBean.java

/**
 * Synchronizes the roles between the application and the identity provider.
 *
 * @param username the user to synchronize the role for
 * @param role the role that should be set on the identity provider
 * @throws PortalServiceException for any errors encountered
 *//*  ww w .  j  a  v a 2  s .com*/
private void synchRoles(String username, Role role) throws PortalServiceException {
    List<String> roles = findRoles(username);

    DirContext ctx = null;
    try {
        ctx = new InitialDirContext(env);

        // remove all roles, we expect only one
        for (String existingRole : roles) {
            if (!existingRole.equals(role.getDescription())) {
                removeRoleAssignment(ctx, username, existingRole);
            }
        }

        // add the new role if needed
        if (!roles.contains(role.getDescription())) {
            ModificationItem[] mods = new ModificationItem[1];
            BasicAttribute m = new BasicAttribute(groupMemberAttr,
                    MessageFormat.format(userDNPattern, username));
            mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, m);
            ctx.modifyAttributes(MessageFormat.format(groupDNPattern, role.getDescription()), mods);
        }
    } catch (NamingException e) {
        throw new PortalServiceConfigurationException("Unable to reset password.", e);
    } finally {
        closeContext(ctx);
    }

}

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 {/*from  w ww .ja  v a 2 s .co m*/
        // 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);
    }
}