Example usage for javax.naming Context PROVIDER_URL

List of usage examples for javax.naming Context PROVIDER_URL

Introduction

In this page you can find the example usage for javax.naming Context PROVIDER_URL.

Prototype

String PROVIDER_URL

To view the source code for javax.naming Context PROVIDER_URL.

Click Source Link

Document

Constant that holds the name of the environment property for specifying configuration information for the service provider to use.

Usage

From source file:org.malaguna.cmdit.service.ldap.LDAPBase.java

public DirContext getDirContext() {
    DirContext ctx = null;/*from ww w.j a  v  a  2 s  . co  m*/
    String cadena = "uid=" + user + "," + context;
    Hashtable<String, String> entorno = new Hashtable<String, String>();

    entorno.put(Context.PROVIDER_URL, server);
    entorno.put(Context.SECURITY_PRINCIPAL, cadena);
    entorno.put(Context.SECURITY_CREDENTIALS, password);
    entorno.put(Context.INITIAL_CONTEXT_FACTORY, initContext);

    try {
        ctx = new InitialDirContext(entorno);
    } catch (NamingException e) {
        logger.error(messages.getMessage("err.ldap.attribute", new Object[] { e }, Locale.getDefault()));
    }

    return ctx;
}

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

void activate(Map<?, ?> configuration) throws NamingException {
    this.idSuffix = (String) configuration.get(CONFIG_ID_SUFFIX);
    this.url = (String) configuration.get(CONFIG_URL);
    this.baseDN = (String) configuration.get(CONFIG_BASE_DN);
    this.userSearchBase = (String) configuration.get(CONFIG_USER_SEARCH_BASE);
    this.userFilter = (String) configuration.get(CONFIG_USER_FILTER);

    String managerDN = (String) configuration.get(CONFIG_MANAGER_DN);
    String managerPassword = (String) configuration.get(CONFIG_MANAGER_PASSWORD);

    searchEnvironment = new Hashtable<String, String>();
    searchEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    searchEnvironment.put(Context.PROVIDER_URL, url);

    if (managerDN != null) {
        searchEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple");
        searchEnvironment.put(Context.SECURITY_PRINCIPAL, managerDN);
        searchEnvironment.put(Context.SECURITY_CREDENTIALS, managerPassword);
    } else//from   w w w . j  av  a2 s .c o  m
        searchEnvironment.put(Context.SECURITY_AUTHENTICATION, "none");
}

From source file:org.jboss.test.NamingUtil.java

/**
 * Returns initial context which is able to perform all JNDI operations.
 * @param serverHost - use getServerHostForURL() from inside JBoss Testsuite
 * @param jndiFactoryUrlSuffix - URL suffix to get proper invoker invoker/JNDIFactory or invoker/HAJNDIFactory
 * @return//  w w w  .  j  a va2s . co m
 * @throws Exception
 */
public static InitialContext getFullInitialContext(String serverHost, String jndiFactoryUrlSuffix)
        throws Exception {

    if (jndiFactoryUrlSuffix == null) {
        jndiFactoryUrlSuffix = JNDI_INVOKER;
    }

    Properties env = new Properties();
    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.HttpNamingContextFactory");

    env.setProperty(Context.PROVIDER_URL, "http://" + serverHost + ":8080/" + jndiFactoryUrlSuffix);
    log.debug("Creating InitialContext with env=" + env);
    InitialContext ctx = new InitialContext(env);

    return ctx;
}

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 va  2  s.co  m

    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:org.hyperic.hq.plugin.netservices.LDAPCollector.java

public void collect() {

    // Setup initial LDAP properties
    Properties env = new Properties();
    Properties props = getProperties();

    // Set our default factory name if one is not given
    String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY);
    if (factoryName == null) {
        env.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    }/* ww w . j  a  v a  2s . c  om*/

    // Set the LDAP url
    if (isSSL()) {
        env.put("java.naming.ldap.factory.socket", LDAPSSLSocketFactory.class.getName());
        env.put(Context.SECURITY_PROTOCOL, "ssl");
    }
    String providerUrl = "ldap://" + getHostname() + ":" + getPort();
    env.setProperty(Context.PROVIDER_URL, providerUrl);

    // For log track
    setSource(providerUrl);

    // Follow referrals automatically
    env.setProperty(Context.REFERRAL, "follow");

    // Base DN
    String baseDN = props.getProperty(PROP_BASEDN);
    if (baseDN == null) {
        setErrorMessage("No Base DN given, refusing login");
        setAvailability(false);
        return;
    }

    // Search filter
    String filter = props.getProperty(PROP_FILTER);

    // Load any information we may need to bind
    String bindDN = props.getProperty(PROP_BINDDN);
    String bindPW = props.getProperty(PROP_BINDPW);
    if (bindDN != null) {
        env.setProperty(Context.SECURITY_PRINCIPAL, bindDN);
        env.setProperty(Context.SECURITY_CREDENTIALS, bindPW);
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    }

    if (log.isDebugEnabled()) {
        log.debug("Using LDAP environment: " + env);
    }

    try {
        startTime();
        InitialLdapContext ctx = new InitialLdapContext(env, null);
        endTime();

        setAvailability(true);

        // If a search filter is specified, run the search and return the
        // number of matches as a metric
        if (filter != null) {
            log.debug("Using LDAP filter=" + filter);
            NamingEnumeration answer = ctx.search(baseDN, filter, getSearchControls());

            long matches = 0;
            while (answer.hasMore()) {
                matches++;
                answer.next();
            }

            setValue("NumberofMatches", matches);
        }
    } catch (Exception e) {
        setAvailability(false);
        if (log.isDebugEnabled()) {
            log.debug("LDAP check failed: " + e, e);
        }

        setErrorMessage("LDAP check failed: " + e);
    }
}

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);
            }/*from  w w  w  . jav a2 s .com*/
        }
    }
    return this.ctx;
}

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

/**
 * Instantiate LDAP based <code>UserManager</code> implementation.
 *///from  ww w .j ava2  s .co m
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: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)");
    }//from  www. j a  va 2  s.  co m
    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.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);// w ww  .  j a  v a 2  s.  com
    }
}

From source file:com.dianping.cat.system.page.login.service.SessionManager.java

public SessionManager() {
    super();/*w  w  w.j a  v  a2s.  c  om*/
    AuthType type = AuthType.valueOf(CatPropertyProvider.INST.getProperty("CAT_AUTH_TYPE", "ADMIN_PWD"));
    switch (type) {
    case NOP:
        tokenCreator = new Function<Credential, Token>() {
            @Override
            public Token apply(Credential credential) {
                String account = credential.getAccount();
                return new Token(account, account);
            }
        };
        break;
    case LDAP:
        final String ldapUrl = CatPropertyProvider.INST.getProperty("CAT_LDAP_URL", null);
        if (StringUtils.isBlank(ldapUrl)) {
            throw new IllegalArgumentException("required CAT_LDAP_URL");
        }
        final String userDnTpl = CatPropertyProvider.INST.getProperty("CAT_LDAP_USER_DN_TPL", null);
        if (StringUtils.isBlank(userDnTpl)) {
            throw new IllegalArgumentException("required CAT_LDAP_USER_DN_TPL");
        }
        final String userDisplayAttr = CatPropertyProvider.INST.getProperty("CAT_LDAP_USER_DISPLAY_ATTR", null);
        final Pattern pattern = Pattern.compile("\\{0}");
        final Matcher userDnTplMatcher = pattern.matcher(userDnTpl);
        final String[] attrs = userDisplayAttr == null ? null : new String[] { userDisplayAttr };
        tokenCreator = new Function<Credential, Token>() {
            @Override
            public Token apply(Credential credential) {
                final String account = credential.getAccount();
                final String pwd = credential.getPassword();
                if (StringUtils.isEmpty(account) || StringUtils.isEmpty(pwd)) {
                    return null;
                }
                Hashtable<String, String> env = new Hashtable<String, String>();
                env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
                env.put(Context.PROVIDER_URL, ldapUrl);// LDAP server
                String userDn = userDnTplMatcher.replaceAll(account);
                env.put(Context.SECURITY_PRINCIPAL, pwd);
                env.put(Context.SECURITY_CREDENTIALS, pwd);
                try {
                    InitialLdapContext context = new InitialLdapContext(env, null);
                    final String baseDn = context.getNameInNamespace();
                    if (userDn.endsWith(baseDn)) {
                        userDn = userDn.substring(0, userDn.length() - baseDn.length() - 1);
                    }
                    String displayName = null;
                    if (attrs != null) {
                        final Attributes attributes = context.getAttributes(userDn, attrs);
                        if (attributes.size() > 0) {
                            displayName = attributes.getAll().next().get().toString();
                        }
                    }

                    return new Token(account, displayName == null ? account : displayName);
                } catch (Exception e) {
                    Cat.logError(e);
                    return null;
                }
            }

        };
        break;
    case ADMIN_PWD:
        final String p = CatPropertyProvider.INST.getProperty("CAT_ADMIN_PWD", "admin");

        tokenCreator = new Function<Credential, Token>() {
            @Override
            public Token apply(Credential credential) {
                String account = credential.getAccount();

                if ("admin".equals(account) && p.equals(credential.getPassword())) {
                    return new Token(account, account);
                }
                return null;
            }

        };
        break;
    }
}