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:eu.europa.esig.dss.client.http.commons.CommonsDataLoader.java

/**
 * This method retrieves data using LDAP protocol.
 * - CRL from given LDAP url, e.g. ldap://ldap.infonotary.com/dc=identity-ca,dc=infonotary,dc=com
 * - ex URL from AIA ldap://xadessrv.plugtests.net/CN=LevelBCAOK,OU=Plugtests_2015-2016,O=ETSI,C=FR?cACertificate;binary
 *
 * @param urlString/*  www . ja  v a 2  s .co m*/
 * @return
 */
private byte[] ldapGet(final String urlString) {

    final Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, urlString);
    try {

        String attributeName = StringUtils.substringAfterLast(urlString, "?");
        if (StringUtils.isEmpty(attributeName)) {
            // default was CRL
            attributeName = "certificateRevocationList;binary";
        }

        final DirContext ctx = new InitialDirContext(env);
        final Attributes attributes = ctx.getAttributes(StringUtils.EMPTY);
        final Attribute attribute = attributes.get(attributeName);
        final byte[] ldapBytes = (byte[]) attribute.get();
        if (ArrayUtils.isEmpty(ldapBytes)) {
            throw new DSSException("Cannot download CRL from: " + urlString);
        }
        return ldapBytes;
    } catch (Exception e) {
        LOG.warn(e.getMessage(), e);
    }
    return null;
}

From source file:org.wso2.carbon.connector.integration.test.ldap.LdapConnectorIntegrationTest.java

public void createSampleEntity() throws Exception {

    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    env.put(Context.PROVIDER_URL, providerUrl);
    env.put(Context.SECURITY_PRINCIPAL, securityPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, securityCredentials);

    DirContext ctx = new InitialDirContext(env);
    Attributes entry = new BasicAttributes();
    Attribute obClassAttr = new BasicAttribute("objectClass");
    obClassAttr.add("inetOrgPerson");
    entry.put(obClassAttr);// w w  w.j a v a2 s  .  c  om

    Attribute mailAttr = new BasicAttribute("mail");
    mailAttr.add(testUserId + "@wso2.com");
    entry.put(mailAttr);

    Attribute passAttr = new BasicAttribute("userPassword");
    passAttr.add("12345");
    entry.put(passAttr);

    Attribute snAttr = new BasicAttribute("sn");
    snAttr.add("dim");
    entry.put(snAttr);

    Attribute cnAttr = new BasicAttribute("cn");
    cnAttr.add("dim");
    entry.put(cnAttr);

    String dn = "uid=" + testUserId + "," + userBase;

    ctx.createSubcontext(dn, entry);
}

From source file:edu.lafayette.metadb.model.userman.UserManDAO.java

/**
 * Get the LDAP DN for a user.//from w w w. j a v a 2s  .  co  m
 * @param searchUser
 * @param searchPassword
 * @param userName
 * @return
 */
@SuppressWarnings("unchecked")
private static String getDN(String searchUser, String searchPassword, String userName) {
    // The resultant DN
    String result;

    // Set up environment for creating initial context
    Hashtable env = new Hashtable(11);
    env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(javax.naming.Context.PROVIDER_URL, Global.LDAP_URL);

    // Use admin credencials for search// Authenticate
    env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "Simple");
    env.put(javax.naming.Context.SECURITY_PRINCIPAL, searchUser);
    env.put(javax.naming.Context.SECURITY_CREDENTIALS, searchPassword);

    DirContext ctx = null;
    try {
        // Create initial context
        ctx = new InitialDirContext(env);
        //MetaDbHelper.note("Created LDAP context");

        Attributes matchAttrs = new BasicAttributes(true);
        matchAttrs.put(new BasicAttribute(Global.LDAP_ID, userName));
        //MetaDbHelper.note("Created attributes");

        // look up attributes
        try {
            //MetaDbHelper.note("Setting up query");

            SearchControls ctrls = new SearchControls();
            ctrls.setSearchScope(Global.LDAP_SCOPE);

            NamingEnumeration<SearchResult> answer = ctx.search(Global.LDAP_URL + Global.LDAP_CONTEXT,
                    "(&({0}={1}))", new Object[] { Global.LDAP_ID, userName }, ctrls);

            //MetaDbHelper.note("NamingEnumeration retrieved");

            while (answer.hasMoreElements()) {
                SearchResult sr = answer.next();
                if (StringUtils.isEmpty(Global.LDAP_CONTEXT)) {
                    result = sr.getName();
                } else {
                    result = (sr.getName() + "," + Global.LDAP_CONTEXT);
                }

                //MetaDbHelper.note("Got DN: "+result);

                return result;
            }
        } catch (NamingException e) {
            MetaDbHelper.logEvent(e);
            //MetaDbHelper.note("LDAP Error: Failed Search");
        }
    } catch (NamingException e) {
        MetaDbHelper.logEvent(e);
        //MetaDbHelper.note("LDAP Error: Failed authentication");
    } finally {
        // Close the context when we're done
        try {
            if (ctx != null)
                ctx.close();
        } catch (NamingException e) {
        }
    }
    // No DN match found
    return null;
}

From source file:com.funambol.LDAP.security.LDAPUserProvisioningOfficer.java

/**
 * return false if user or password is wrong
 *    //from w w  w.ja va2s  .  co m
 * here we expand attributes: %u, %d, %s
 *    if defined userSearch, retrieve user's DN  and try to bind with it
 * @param username
 * @param password
 * @return
 */
private boolean ldapBind(String username, String password) {
    String userDN = null;
    try {
        TempParams t = new TempParams();
        // if username  is an email substitute %u e %d in baseDn:  
        expandSearchAndBaseDn(username, t);

        // setup the default LdapInterface configured with bean data
        ldapInterface = LDAPManagerFactory.createLdapInterface(getLdapInterfaceClassName());
        ldapInterface.init(getLdapUrl(), getBaseDn(), getSearchBindDn(), getSearchBindPassword(),
                isFollowReferral(), isConnectionPooling(), null);

        // set the userDN when custom user search
        if (!StringUtils.isEmpty(getUserSearch())) {
            // customize the field used to search the user.

            SearchResult sr = ldapInterface.searchOneEntry(getUserSearch(), new String[] { "dn" },
                    SearchControls.SUBTREE_SCOPE);

            if (sr == null) {
                log.info("Username " + username + " not found");
                return false;
            }

            userDN = sr.getNameInNamespace().trim();
            log.info("binding with dn:" + userDN);

        }
        // on failure, set the user DN with append
        if (userDN == null) {
            userDN = "uid=" + username + "," + baseDn;
        }
    } catch (Exception e) {
        log.error("Can't instantiate LdapInterface: " + e.getMessage());
        return false;
    }
    // Set up environment for creating 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, getLdapUrl());

    // Authenticate as  User and password  
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, userDN);
    env.put(Context.SECURITY_CREDENTIALS, password);

    try {
        DirContext ctx = new InitialDirContext(env);
        log.debug(ctx.lookup(userDN));
        ctx.close();
    } catch (AuthenticationException e) {
        log.info("User not authenticated: " + e.getMessage());
        return false;
    } catch (NamingException e) {
        log.warn("User not authenticated: problem while accessing ldap " + e.getMessage());
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:ru.runa.wfe.security.logic.LdapLogic.java

private DirContext getContext() throws NamingException {
    Hashtable<String, String> env = new Hashtable<>(LdapProperties.getAllProperties());
    return new InitialDirContext(env);
}

From source file:org.apache.openaz.xacml.admin.view.components.LDAPPIPConfigurationComponent.java

protected void testLDAPConnection() {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, this.textFieldFactory.getValue());
    env.put(Context.PROVIDER_URL, this.textFieldProviderURL.getValue());
    env.put(Context.SECURITY_PRINCIPAL, this.textFieldPrincipal.getValue());
    env.put(Context.SECURITY_CREDENTIALS, this.textFieldCredentials.getValue());

    String auth = this.comboBoxAuthentication.getValue().toString();
    env.put(Context.SECURITY_AUTHENTICATION, auth);
    ///*  w  w w  .  ja  v a  2 s  . c  om*/
    // Do we need to do anything?
    //
    /*
    if (auth.equals(LDAP_AUTH_ANONYMOUS)) {
               
    } else if (auth.equals(LDAP_AUTH_SIMPLE)) {
               
    } else if (auth.equals(LDAP_AUTH_SASL)) {
               
    }
    */

    DirContext ctx = null;
    try {
        ctx = new InitialDirContext(env);
        new Notification("Success!", "Connection Established!", Type.HUMANIZED_MESSAGE, true)
                .show(Page.getCurrent());
    } catch (NamingException e) {
        logger.error(e);
        new Notification("Connection Failed", "<br/>" + e.getLocalizedMessage(), Type.ERROR_MESSAGE, true)
                .show(Page.getCurrent());
    } finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (NamingException idontcare) { //NOPMD
        }
    }
}

From source file:org.apereo.portal.groups.ldap.LDAPGroupStore.java

protected DirContext getConnection() {
    //JNDI boilerplate to connect to an initial context
    DirContext context = (DirContext) contexts.get("context");
    if (context == null) {
        Hashtable jndienv = new Hashtable();
        jndienv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        jndienv.put(Context.SECURITY_AUTHENTICATION, "simple");
        if (url.startsWith("ldaps")) { // Handle SSL connections
            String newurl = url.substring(0, 4) + url.substring(5);
            jndienv.put(Context.SECURITY_PROTOCOL, "ssl");
            jndienv.put(Context.PROVIDER_URL, newurl);
        } else {/*from  ww  w .  j  a v a 2s  .  c  o m*/
            jndienv.put(Context.PROVIDER_URL, url);
        }
        if (logonid != null)
            jndienv.put(Context.SECURITY_PRINCIPAL, logonid);
        if (logonpassword != null)
            jndienv.put(Context.SECURITY_CREDENTIALS, logonpassword);
        try {
            context = new InitialDirContext(jndienv);
        } catch (NamingException nex) {
            log.error("LDAPGroupStore: unable to get context", nex);
        }
        contexts.put("context", context);
    }
    return context;
}

From source file:org.wso2.carbon.connector.integration.test.ldap.LdapConnectorIntegrationTest.java

public void deleteSampleEntry() throws Exception {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    env.put(Context.PROVIDER_URL, providerUrl);
    env.put(Context.SECURITY_PRINCIPAL, securityPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, securityCredentials);

    DirContext ctx = new InitialDirContext(env);
    String dn = "uid=" + testUserId + "," + userBase;
    ctx.destroySubcontext(dn);//w w  w .  ja  v a 2 s  . c  o m
}

From source file:org.lsc.jndi.JndiServices.java

private static String lookupLdapSrvThroughDNS(String hostname) {
    Properties env = new Properties();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    env.put("java.naming.provider.url", "dns:");
    DirContext ctx;/*from   w w  w.j a  v  a  2s .c  o m*/
    try {
        ctx = new InitialDirContext(env);
        if (ctx != null) {
            Attributes attrs = ctx.getAttributes(hostname, new String[] { "SRV" });
            String[] attributes = ((String) attrs.getAll().next().get()).split(" ");
            return attributes[3] + ":" + attributes[2];
        }
    } catch (NamingException e) {
    }
    return hostname + ":389";
}