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:com.photon.phresco.ldap.impl.LDAPManagerImpl.java

@Override
public User authenticate(Credentials credentials) throws PhrescoException {
    if (isDebugEnabled) {
        S_LOGGER.debug("Entering Method LDAPManagerImpl.authenticate(Credentials credentials)");
    }// w  ww.ja va 2 s  .  c om
    String userName = credentials.getUsername();
    String passwordEncoded = credentials.getPassword();
    byte[] decodedBytes = Base64.decodeBase64(passwordEncoded);
    String password = new String(decodedBytes);
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, ldapConfig.getLdapContextFactory());
    env.put(Context.PROVIDER_URL, ldapConfig.getLdapUrl());
    env.put(Context.SECURITY_PRINCIPAL, getUserPrincipal(userName));
    env.put(Context.SECURITY_CREDENTIALS, password);

    DirContext dc = null;
    try {
        dc = new InitialDirContext(env);
        if (isDebugEnabled) {
            S_LOGGER.debug("authenticate() Login Success for " + userName);
        }
        return getUser(credentials, dc);
    } catch (Exception e) {
        e.printStackTrace();
        if (isDebugEnabled) {
            S_LOGGER.debug("authenticate() Login Failed for " + userName);
        }
        return new User();
    } finally {
        try {
            if (dc != null) {
                dc.close();
            }
        } catch (NamingException e) {
            throw new PhrescoException(e);
        }
    }
}

From source file:de.sub.goobi.helper.ldap.Ldap.java

/**
 * create new user in LDAP-directory./*from  w  w  w . j  a  va2  s  .  c o  m*/
 *
 * @param inBenutzer
 *            User object
 * @param inPasswort
 *            String
 */
public void createNewUser(User inBenutzer, String inPasswort)
        throws NamingException, NoSuchAlgorithmException, IOException {

    if (!ConfigCore.getBooleanParameter("ldap_readonly", false)) {
        Hashtable<String, String> env = getLdapConnectionSettings();
        env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
        env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));

        LdapUser dr = new LdapUser();
        dr.configure(inBenutzer, inPasswort, getNextUidNumber());
        DirContext ctx = new InitialDirContext(env);
        ctx.bind(getUserDN(inBenutzer), dr);
        ctx.close();
        setNextUidNumber();
        Helper.setMeldung(null, Helper.getTranslation("ldapWritten") + " "
                + serviceManager.getUserService().getFullName(inBenutzer), "");
        /*
         * check if HomeDir exists, else create it
         */
        logger.debug("HomeVerzeichnis pruefen");
        URI homePath = URI.create(getUserHomeDirectory(inBenutzer));
        if (!new File(homePath).exists()) {
            logger.debug("HomeVerzeichnis existiert noch nicht");
            serviceManager.getFileService().createDirectoryForUser(homePath, inBenutzer.getLogin());
            logger.debug("HomeVerzeichnis angelegt");
        } else {
            logger.debug("HomeVerzeichnis existiert schon");
        }
    } else {
        Helper.setMeldung(Helper.getTranslation("ldapIsReadOnly"));
    }
}

From source file:org.apache.ftpserver.usermanager.LdapUserManager.java

/**
 * Instantiate LDAP based <code>UserManager</code> implementation.
 *///  w w w .  ja v a2s  .  c  om
public void configure(Configuration config) throws FtpException {

    try {

        // get admin name 
        m_adminName = config.getString("admin", "admin");

        // get ldap parameters
        String url = config.getString("ldap-url");
        String admin = config.getString("ldap-admin-dn");
        String password = config.getString("ldap-admin-password");
        String auth = config.getString("ldap-authentication", "simple");

        m_userBaseDn = config.getString("ldap-user-base-dn");

        // create connection
        Properties adminEnv = new Properties();
        adminEnv.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        adminEnv.setProperty(Context.PROVIDER_URL, url);
        adminEnv.setProperty(Context.SECURITY_AUTHENTICATION, auth);
        adminEnv.setProperty(Context.SECURITY_PRINCIPAL, admin);
        adminEnv.setProperty(Context.SECURITY_CREDENTIALS, password);
        m_adminContext = new InitialDirContext(adminEnv);

        // create objectClass attribute
        m_objClassAttr = new BasicAttribute(OBJ_CLASS, false);
        m_objClassAttr.add("javaObject");
        m_objClassAttr.add("top");

        m_log.info("LDAP user manager opened.");
    } catch (FtpException ex) {
        throw ex;
    } catch (Exception ex) {
        m_log.fatal("LdapUserManager.configure()", ex);
        throw new FtpException("LdapUserManager.configure()", ex);
    }
}

From source file:org.hyperic.hq.plugin.openldap.OpenLDAPMeasurementPlugin.java

public DirContext getDirContext(Properties props) throws NamingException {
    if (this.ctx == null) {
        synchronized (this) {
            if (this.ctx == null) {
                log.debug("[getDirContext] creating new connection");
                Collection rtn = new TreeSet();
                Hashtable ldapEnv = new Hashtable();
                String ldapDriver = props.getProperty("ldapDriver"),
                        ldapHostURL = props.getProperty("ldapHostURL"),
                        ldapAuthType = props.getProperty("ldapAuthType"),
                        ldapPasswd = props.getProperty("ldapPasswd"),
                        ldapTreePathToDN = props.getProperty("ldapTreePathToDN");
                ldapTreePathToDN = (ldapTreePathToDN == null) ? "" : ldapTreePathToDN;
                ldapPasswd = (ldapPasswd == null) ? "" : ldapPasswd;
                ldapPasswd = (ldapPasswd.matches("^\\s*$")) ? "" : ldapPasswd;
                ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, ldapDriver);
                ldapEnv.put(Context.PROVIDER_URL, ldapHostURL);
                ldapEnv.put(Context.SECURITY_AUTHENTICATION, ldapAuthType);
                ldapEnv.put(Context.SECURITY_PRINCIPAL, ldapTreePathToDN);
                ldapEnv.put(Context.SECURITY_CREDENTIALS, ldapPasswd);
                this.ctx = new InitialDirContext(ldapEnv);
            }// w ww .j  a  v a 2  s.c  om
        }
    }
    return this.ctx;
}

From source file:de.interseroh.report.test.security.LdapServerTest.java

@Test
public void testJndiSun() throws NamingException {
    Hashtable<String, String> contextParams = new Hashtable<String, String>();
    contextParams.put(Context.PROVIDER_URL, "ldap://ldap.xxx:389");
    contextParams.put(Context.SECURITY_PRINCIPAL, USER_LDAP);
    contextParams.put(Context.SECURITY_CREDENTIALS, PASSWORD_LDAP);
    contextParams.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    DirContext dirContext = new InitialDirContext(contextParams);

    Attributes attributes = dirContext.getAttributes("", new String[] { "namingContexts" });
    Attribute attribute = attributes.get("namingContexts");
    NamingEnumeration<?> all = attribute.getAll();
    while (all.hasMore()) {
        String next = (String) all.next();
        logger.info(next);/*from w  w w  . j a v a2 s .  co m*/
    }
}

From source file:info.globalbus.dkim.DKIMUtil.java

public boolean checkDNSForPublickey(String signingDomain, String selector) throws DKIMSignerException {

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    String recordname = selector + "._domainkey." + signingDomain;
    String value = null;/*from ww w  .  java  2  s . c om*/

    try {
        DirContext dnsContext = new InitialDirContext(env);

        javax.naming.directory.Attributes attribs = dnsContext.getAttributes(recordname,
                new String[] { "TXT" });
        javax.naming.directory.Attribute txtrecord = attribs.get("txt");

        if (txtrecord == null) {
            throw new DKIMSignerException("There is no TXT record available for " + recordname);
        }

        // "v=DKIM1; g=*; k=rsa; p=MIGfMA0G ..."
        value = (String) txtrecord.get();

    } catch (NamingException ne) {
        throw new DKIMSignerException("Selector lookup failed", ne);
    }

    if (value == null) {
        throw new DKIMSignerException("Value of RR " + recordname + " couldn't be retrieved");
    }

    // try to read public key from RR
    String[] tags = value.split(";");
    for (String tag : tags) {
        tag = tag.trim();
        if (tag.startsWith("p=")) {

            try {
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");

                // decode public key, FSTODO: convert to DER format
                PKCS8EncodedKeySpec pubSpec = new PKCS8EncodedKeySpec(tag.substring(2).getBytes());
                keyFactory.generatePublic(pubSpec);
            } catch (NoSuchAlgorithmException nsae) {
                throw new DKIMSignerException("RSA algorithm not found by JVM");
            } catch (InvalidKeySpecException ikse) {
                throw new DKIMSignerException(
                        "The public key " + tag + " in RR " + recordname + " couldn't be decoded.");
            }

            // FSTODO: create test signature with privKey and test
            // validation with pubKey to check on a valid key pair

            return true;
        }
    }

    throw new DKIMSignerException("No public key available in " + recordname);
}

From source file:org.javlo.external.agitos.dkim.DKIMUtil.java

public boolean checkDNSForPublickey(String signingDomain, String selector) throws DKIMSignerException {

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    String recordname = selector + "._domainkey." + signingDomain;
    String value = null;/*from  ww w  .  jav a  2s .  c om*/

    try {
        DirContext dnsContext = new InitialDirContext(env);

        javax.naming.directory.Attributes attribs = dnsContext.getAttributes(recordname,
                new String[] { "TXT" });
        javax.naming.directory.Attribute txtrecord = attribs.get("txt");

        if (txtrecord == null) {
            throw new DKIMSignerException("There is no TXT record available for " + recordname);
        }

        // "v=DKIM1; g=*; k=rsa; p=MIGfMA0G ..."
        value = (String) txtrecord.get();

    } catch (NamingException ne) {
        throw new DKIMSignerException("Selector lookup failed", ne);
    }

    if (value == null) {
        throw new DKIMSignerException("Value of RR " + recordname + " couldn't be retrieved");
    }

    // try to read public key from RR
    String[] tags = value.split(";");
    for (String tag : tags) {
        tag = tag.trim();
        if (tag.startsWith("p=")) {

            try {
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");

                // decode public key, FSTODO: convert to DER format
                PKCS8EncodedKeySpec pubSpec = new PKCS8EncodedKeySpec(tag.substring(2).getBytes());
                RSAPrivateKey pubKey = (RSAPrivateKey) keyFactory.generatePublic(pubSpec);
            } catch (NoSuchAlgorithmException nsae) {
                throw new DKIMSignerException("RSA algorithm not found by JVM");
            } catch (InvalidKeySpecException ikse) {
                throw new DKIMSignerException(
                        "The public key " + tag + " in RR " + recordname + " couldn't be decoded.");
            }

            // FSTODO: create test signature with privKey and test validation with pubKey to check on a valid key pair

            return true;
        }
    }

    throw new DKIMSignerException("No public key available in " + recordname);
}

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

public boolean authenticateUser(String userLogin, UserEdit edit, String password) {
    Hashtable env = new Hashtable();
    InitialDirContext ctx;/* w ww .j  a  v  a2 s. c om*/

    String INIT_CTX = "com.sun.jndi.ldap.LdapCtxFactory";
    String MY_HOST = getLdapHost() + ":" + getLdapPort();
    String cn;
    boolean returnVal = false;

    if (!password.equals("")) {

        env.put(Context.INITIAL_CONTEXT_FACTORY, INIT_CTX);
        env.put(Context.PROVIDER_URL, MY_HOST);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_CREDENTIALS, "secret");

        String[] returnAttribute = { "ou" };
        SearchControls srchControls = new SearchControls();
        srchControls.setReturningAttributes(returnAttribute);
        srchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String searchFilter = "(&(objectclass=person)(uid=" + escapeSearchFilterTerm(userLogin) + "))";

        try {
            ctx = new InitialDirContext(env);
            NamingEnumeration answer = ctx.search(getBasePath(), searchFilter, srchControls);
            String trobat = "false";

            while (answer.hasMore() && trobat.equals("false")) {

                SearchResult sr = (SearchResult) answer.next();
                String dn = sr.getName().toString() + "," + getBasePath();

                // Second binding
                Hashtable authEnv = new Hashtable();
                try {
                    authEnv.put(Context.INITIAL_CONTEXT_FACTORY, INIT_CTX);
                    authEnv.put(Context.PROVIDER_URL, MY_HOST);
                    authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
                    authEnv.put(Context.SECURITY_PRINCIPAL, sr.getName() + "," + getBasePath());
                    authEnv.put(Context.SECURITY_CREDENTIALS, password);
                    try {
                        DirContext authContext = new InitialDirContext(authEnv);
                        returnVal = true;
                        trobat = "true";
                        authContext.close();
                    } catch (AuthenticationException ae) {
                        M_log.info("Access forbidden");
                    }

                } catch (NamingException namEx) {
                    M_log.info("User doesn't exist");
                    returnVal = false;
                    namEx.printStackTrace();
                }
            }
            if (trobat.equals("false"))
                returnVal = false;

        } catch (NamingException namEx) {
            namEx.printStackTrace();
            returnVal = false;
        }
    }
    return returnVal;
}

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.LDAPInitialDirContextFactoryImpl.java

/**
 * {@inheritDoc}/*from   w ww.  j  a  v  a 2s  . c  om*/
 */
@Override
public void afterPropertiesSet() throws Exception {
    // handled as part of setter in default class
    if (this.poolSystemProperties != null) {
        for (final Entry<String, String> entry : this.poolSystemProperties.entrySet()) {
            System.setProperty(entry.getKey(), entry.getValue());
        }
    }

    // check anonymous bind
    final Map<String, String> config = new HashMap<>(this.authenticatedEnvironment.size());
    config.putAll(this.authenticatedEnvironment);
    config.remove(Context.SECURITY_PRINCIPAL);
    config.remove(Context.SECURITY_CREDENTIALS);

    if (this.isSSLSocketFactoryRequired(config)) {
        final KeyStore trustStore = this.initTrustStore();
        ThreadSafeSSLSocketFactory.initTrustedSSLSocketFactory(trustStore);
        config.put("java.naming.ldap.factory.socket", ThreadSafeSSLSocketFactory.class.getName());
    }

    try {
        new InitialDirContext(new Hashtable<>(config));
        LOGGER.warn("LDAP server supports anonymous bind {}", config.get(Context.PROVIDER_URL));
    } catch (javax.naming.AuthenticationException | AuthenticationNotSupportedException ax) {
        // NO-OP - expected
    } catch (final NamingException nx) {
        LOGGER.error("Unable to connect to LDAP Server; check LDAP configuration", nx);
        return;
    }

    // Simple DN and password
    config.put(Context.SECURITY_PRINCIPAL, "daftAsABrush");
    config.put(Context.SECURITY_CREDENTIALS, "daftAsABrush");

    try {
        new InitialDirContext(new Hashtable<>(config));
        throw new AuthenticationException("The ldap server at " + config.get(Context.PROVIDER_URL)
                + " falls back to use anonymous bind if invalid security credentials are presented. This is not supported.");
    } catch (javax.naming.AuthenticationException | AuthenticationNotSupportedException ax) {
        LOGGER.info("LDAP server does not fall back to anonymous bind for a string uid and password at {}",
                config.get(Context.PROVIDER_URL));
    } catch (final NamingException nx) {
        LOGGER.info("LDAP server does not support simple string user ids and invalid credentials at {}",
                config.get(Context.PROVIDER_URL));
    }

    // DN and password
    config.put(Context.SECURITY_PRINCIPAL, "cn=daftAsABrush,dc=woof");
    config.put(Context.SECURITY_CREDENTIALS, "daftAsABrush");
    try {
        new InitialDirContext(new Hashtable<>(config));
        throw new AuthenticationException("The ldap server at " + config.get(Context.PROVIDER_URL)
                + " falls back to use anonymous bind if invalid security credentials are presented. This is not supported.");
    } catch (javax.naming.AuthenticationException | AuthenticationNotSupportedException ax) {
        LOGGER.info("LDAP server does not fall back to anonymous bind for a simple dn and password at {}",
                config.get(Context.PROVIDER_URL));
    } catch (final NamingException nx) {
        LOGGER.info("LDAP server does not support simple DN and invalid credentials at {}",
                config.get(Context.PROVIDER_URL));
    }

    // Check more if we have a real principal we expect to work
    final String principal = this.defaultEnvironment.get(Context.SECURITY_PRINCIPAL);
    if (principal != null) {
        config.put(Context.SECURITY_PRINCIPAL, principal);
        config.put(Context.SECURITY_CREDENTIALS, "sdasdasdasdasd123123123");

        try {
            new InitialDirContext(new Hashtable<>(config));
            throw new AuthenticationException("The ldap server at " + config.get(Context.PROVIDER_URL)
                    + " falls back to use anonymous bind for a known principal if invalid security credentials are presented. This is not supported.");
        } catch (final javax.naming.AuthenticationException ax) {
            LOGGER.info(
                    "LDAP server does not fall back to anonymous bind for known principal and invalid password at {}",
                    config.get(Context.PROVIDER_URL));
        } catch (final AuthenticationNotSupportedException ax) {
            LOGGER.info("LDAP server does not support the required authentication mechanism");
        } catch (final NamingException nx) {
            // NO-OP - covered in previous checks
        }
    }
}

From source file:org.eclipselabs.etrack.util.security.ldap.impl.LdapService.java

@Override
public NamingEnumeration<SearchResult> find(int scope, String path, String filter) throws NamingException {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(scope);
    String searchPath = path != null && !path.isEmpty() ? path + "," + baseDN : baseDN;

    InitialDirContext searchContext = new InitialDirContext(searchEnvironment);
    NamingEnumeration<SearchResult> searchResults = searchContext.search(searchPath, filter, searchControls);
    searchContext.close();//ww w .  jav a 2s  .  c  om
    return searchResults;
}