Example usage for javax.naming Context SECURITY_PRINCIPAL

List of usage examples for javax.naming Context SECURITY_PRINCIPAL

Introduction

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

Prototype

String SECURITY_PRINCIPAL

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

Click Source Link

Document

Constant that holds the name of the environment property for specifying the identity of the principal for authenticating the caller to the service.

Usage

From source file:org.tolven.ldapmgr.LDAPMgrPlugin.java

private DirContext getContext() {
    char[] rootPassword = getPassword(getTolvenConfigWrapper().getLDAPServerRootPasswordId());
    if (rootPassword == null) {
        throw new RuntimeException(
                "LDAP password is null for alias: " + getTolvenConfigWrapper().getLDAPServerRootPasswordId());
    }/*from  ww  w . ja  v  a  2  s  . co m*/
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, getProviderURL());
    env.put(Context.SECURITY_PRINCIPAL, getTolvenConfigWrapper().getLDAPServerRootUser());
    env.put(Context.SECURITY_CREDENTIALS, new String(rootPassword));
    try {
        return new InitialDirContext(env);
    } catch (NamingException ex) {
        throw new RuntimeException("Could not create an IntialDirContext", ex);
    }
}

From source file:org.olat.ldap.manager.LDAPLoginManagerImpl.java

/**
 * //w w w  . ja va  2  s. co  m
 * Connect to LDAP with the User-Name and Password given as parameters
 * 
 * Configuration: LDAP URL = ldapContext.xml (property=ldapURL) LDAP Base =
 * ldapContext.xml (property=ldapBase) LDAP Attributes Map =
 * ldapContext.xml (property=userAttrs)
 * 
 * 
 * @param uid The users LDAP login name (can't be null)
 * @param pwd The users LDAP password (can't be null)
 * 
 * @return After successful bind Attributes otherwise NULL
 * 
 * @throws NamingException
 */
@Override
public Attributes bindUser(String uid, String pwd, LDAPError errors) {
    // get user name, password and attributes
    String ldapUrl = ldapLoginModule.getLdapUrl();
    String[] userAttr = syncConfiguration.getUserAttributes();

    if (uid == null || pwd == null) {
        if (log.isDebug())
            log.debug("Error when trying to bind user, missing username or password. Username::" + uid
                    + " pwd::" + pwd);
        errors.insert("Username and password must be selected");
        return null;
    }

    LdapContext ctx = bindSystem();
    if (ctx == null) {
        errors.insert("LDAP connection error");
        return null;
    }
    String userDN = ldapDao.searchUserDN(uid, ctx);
    if (userDN == null) {
        log.info("Error when trying to bind user with username::" + uid + " - user not found on LDAP server"
                + (ldapLoginModule.isCacheLDAPPwdAsOLATPwdOnLogin() ? ", trying with OLAT login provider"
                        : ""));
        errors.insert("Username or password incorrect");
        return null;
    }

    // Ok, so far so good, user exists. Now try to fetch attributes using the
    // users credentials
    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);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, userDN);
    env.put(Context.SECURITY_CREDENTIALS, pwd);
    if (ldapLoginModule.getLdapConnectionTimeout() != null) {
        env.put(TIMEOUT_KEY, ldapLoginModule.getLdapConnectionTimeout().toString());
    }
    if (ldapLoginModule.isSslEnabled()) {
        enableSSL(env);
    }

    try {
        Control[] connectCtls = new Control[] {};
        LdapContext userBind = new InitialLdapContext(env, connectCtls);
        Attributes attributes = userBind.getAttributes(userDN, userAttr);
        userBind.close();
        return attributes;
    } catch (AuthenticationException e) {
        log.info("Error when trying to bind user with username::" + uid + " - invalid LDAP password");
        errors.insert("Username or password incorrect");
        return null;
    } catch (NamingException e) {
        log.error("NamingException when trying to get attributes after binding user with username::" + uid, e);
        errors.insert("Username or password incorrect");
        return null;
    }
}

From source file:org.apache.synapse.transport.jms.JMSConnectionFactory.java

/**
 * Begin [or restart] listening for messages on the list of destinations associated
 * with this connection factory. (Called during Axis2 initialization of
 * the Transport receivers, or after a disconnection has been detected)
 *
 * When called from the JMS transport sender, this call simply acquires the actual
 * JMS connection factory from the JNDI, creates a new connection and starts it.
 *
 * @throws JMSException on exceptions/*from  ww  w  . j a  v  a 2  s .  c  o  m*/
 * @throws NamingException on exceptions
 */
public synchronized void connectAndListen() throws JMSException, NamingException {

    // if this is a reconnection/re-initialization effort after the detection of a
    // disconnection, close all sessions and the CF connection and re-initialize
    if (connection != null) {
        log.info("Re-initializing the JMS connection factory : " + name);

        Iterator sessionIter = jmsSessions.values().iterator();
        while (sessionIter.hasNext()) {
            try {
                ((Session) sessionIter.next()).close();
            } catch (JMSException ignore) {
            }
        }
        try {
            connection.stop();
        } catch (JMSException ignore) {
        }

    } else {
        if (log.isDebugEnabled()) {
            log.debug("Initializing the JMS connection factory : " + name);
        }
    }

    // get the CF reference freshly [again] from JNDI
    context = new InitialContext(jndiProperties);
    conFactory = (ConnectionFactory) context.lookup(connFactoryJNDIName);
    log.info("Connected to the JMS connection factory : " + connFactoryJNDIName);

    try {
        ConnectionFactory conFac = null;
        QueueConnectionFactory qConFac = null;
        TopicConnectionFactory tConFac = null;
        if (JMSConstants.DESTINATION_TYPE_QUEUE.equals(getConnectionFactoryType())) {
            qConFac = (QueueConnectionFactory) conFactory;
        } else if (JMSConstants.DESTINATION_TYPE_TOPIC.equals(getConnectionFactoryType())) {
            tConFac = (TopicConnectionFactory) conFactory;
        } else {
            handleException("Unable to determine type of Connection Factory - i.e. Queue/Topic", null);
        }

        String user = (String) jndiProperties.get(Context.SECURITY_PRINCIPAL);
        String pass = (String) jndiProperties.get(Context.SECURITY_CREDENTIALS);

        if (user != null && pass != null) {
            if (qConFac != null) {
                connection = qConFac.createQueueConnection(user, pass);
            } else if (tConFac != null) {
                connection = tConFac.createTopicConnection(user, pass);
            }
        } else {
            if (qConFac != null) {
                connection = qConFac.createQueueConnection();
            } else if (tConFac != null) {
                connection = tConFac.createTopicConnection();
            }
        }

        connection.setExceptionListener(this);

    } catch (JMSException e) {
        handleException("Error connecting to Connection Factory : " + connFactoryJNDIName, e);
    }

    Iterator destJNDINameIter = serviceJNDINameMapping.keySet().iterator();
    while (destJNDINameIter.hasNext()) {
        String destJNDIName = (String) destJNDINameIter.next();
        String destinationType = (String) destinationTypeMapping.get(destJNDIName);
        startListeningOnDestination(destJNDIName, destinationType);
    }

    connection.start(); // indicate readyness to start receiving messages
    log.info("Connection factory : " + name + " initialized...");
}

From source file:com.liferay.portal.action.LoginAction.java

public static void login(HttpServletRequest req, HttpServletResponse res, String login, String password,
        boolean rememberMe) throws Exception {

    CookieKeys.validateSupportCookie(req);

    HttpSession ses = req.getSession();// ww  w .  j a v  a  2s  .  c  o m

    long userId = GetterUtil.getLong(login);

    int authResult = Authenticator.FAILURE;

    Company company = PortalUtil.getCompany(req);

    //
    boolean ldaplogin = false;
    if (PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_ENABLED).equals("true")) {
        LdapContext ctx = PortalLDAPUtil.getContext(company.getCompanyId());
        String accountname = "";
        try {
            User user1 = UserLocalServiceUtil.getUserByScreenName(company.getCompanyId(), login);
            Properties env = new Properties();

            String baseProviderURL = PrefsPropsUtil.getString(company.getCompanyId(),
                    PropsUtil.LDAP_BASE_PROVIDER_URL);
            String userDN = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_USERS_DN);
            String baseDN = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_BASE_DN);
            String filter = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_SEARCH_FILTER);
            filter = StringUtil.replace(filter,
                    new String[] { "@company_id@", "@email_address@", "@screen_name@", "@user_id@" },
                    new String[] { String.valueOf(company.getCompanyId()), "", login, login });
            try {
                SearchControls cons = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0, null, false,
                        false);

                NamingEnumeration enu = ctx.search(userDN, filter, cons);
                if (enu.hasMoreElements()) {
                    SearchResult result = (SearchResult) enu.nextElement();
                    accountname = result.getName();
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }

            env.put(Context.INITIAL_CONTEXT_FACTORY, PrefsPropsUtil.getString(PropsUtil.LDAP_FACTORY_INITIAL));
            env.put(Context.PROVIDER_URL, LDAPUtil.getFullProviderURL(baseProviderURL, baseDN));
            env.put(Context.SECURITY_PRINCIPAL, accountname + "," + userDN);
            env.put(Context.SECURITY_CREDENTIALS, password);

            new InitialLdapContext(env, null);
            ldaplogin = true;
            System.out.println("LDAP Login");
        } catch (Exception e) {
            SessionErrors.add(req, "ldapAuthentication");
            e.printStackTrace();
            System.out.println("LDAP error login");
            return;
        }
    }

    //

    Map headerMap = new HashMap();

    Enumeration enu1 = req.getHeaderNames();

    while (enu1.hasMoreElements()) {
        String name = (String) enu1.nextElement();

        Enumeration enu2 = req.getHeaders(name);

        List headers = new ArrayList();

        while (enu2.hasMoreElements()) {
            String value = (String) enu2.nextElement();

            headers.add(value);
        }

        headerMap.put(name, (String[]) headers.toArray(new String[0]));
    }

    Map parameterMap = req.getParameterMap();

    if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_EA)) {
        authResult = UserLocalServiceUtil.authenticateByEmailAddress(company.getCompanyId(), login, password,
                headerMap, parameterMap);

        userId = UserLocalServiceUtil.getUserIdByEmailAddress(company.getCompanyId(), login);
    } else if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_SN)) {
        authResult = UserLocalServiceUtil.authenticateByScreenName(company.getCompanyId(), login, password,
                headerMap, parameterMap);

        userId = UserLocalServiceUtil.getUserIdByScreenName(company.getCompanyId(), login);
    } else if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_ID)) {
        authResult = UserLocalServiceUtil.authenticateByUserId(company.getCompanyId(), userId, password,
                headerMap, parameterMap);
    }

    boolean OTPAuth = false;

    if (GetterUtil.getBoolean(PropsUtil.get("use.yubicoauthentication"), false) == true) {
        String otppasswd = ParamUtil.getString(req, "otp");
        String userslist = GetterUtil.getString(PropsUtil.get("yubico.users.not.require.otp"), "root");
        if (userslist.contains(login)) {
            authResult = Authenticator.SUCCESS;
        } else {
            OTPAuth = SecurityUtils.verifyOTP(otppasswd, login);
            if (authResult == Authenticator.SUCCESS && OTPAuth) {
                authResult = Authenticator.SUCCESS;
            } else {
                authResult = Authenticator.FAILURE;
            }
        }
    }

    if (PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_ENABLED).equals("true")) {
        if (!login.equals("root")) {
            if (ldaplogin) {
                authResult = Authenticator.SUCCESS;
            }
        }
    }

    if (authResult == Authenticator.SUCCESS) {

        boolean loginViaPortal = true;

        setLoginCookies(req, res, ses, userId, rememberMe);
        // login to epsos
        String language = GeneralUtils.getLocale(req);
        SpiritEhrWsClientInterface webService = EpsosHelperService.getInstance().getWebService(req);

        InitUserObj initUserObj = EpsosHelperImpl.createEpsosUserInformation(req, res, language, webService,
                userId, company.getCompanyId(), login, loginViaPortal);
        SpiritUserClientDto usr = initUserObj.getUsr();
        Assertion assertion = initUserObj.getAssertion();

        if (Validator.isNotNull(usr)) {
            req.getSession().setAttribute(EpsosHelperService.EPSOS_LOGIN_INFORMATION_ASSERTIONID,
                    assertion.getID());
            req.getSession().setAttribute(EpsosHelperService.EPSOS_LOGIN_INFORMATION_ASSERTION, assertion);
            req.getSession().setAttribute(EPSOS_LOGIN_INFORMATION_ATTRIBUTE, usr);
        } else {
            SessionErrors.add(req, "User doesn't belong to epSOS role so you can't login");
        }

        if (Validator.isNull(usr) && (!(login.equals("root")))) {
            try {
                Cookie cookie = new Cookie(CookieKeys.ID, StringPool.BLANK);
                cookie.setMaxAge(0);
                cookie.setPath("/");

                CookieKeys.addCookie(res, cookie);

                cookie = new Cookie(CookieKeys.PASSWORD, StringPool.BLANK);
                cookie.setMaxAge(0);
                cookie.setPath("/");

                CookieKeys.addCookie(res, cookie);

                try {
                    ses.invalidate();
                } catch (Exception e) {
                }

            } catch (Exception e) {
                req.setAttribute(PageContext.EXCEPTION, e);

            }
            throw new AuthException();

        }

    } else {
        throw new AuthException();
    }
}

From source file:hudson.security.LDAPSecurityRealm.java

/**
 * Infer the root DN./* ww  w. j  a va  2  s . c  om*/
 *
 * @return null if not found.
 */
private String inferRootDN(String server) {
    try {
        Hashtable<String, String> props = new Hashtable<String, String>();
        if (managerDN != null) {
            props.put(Context.SECURITY_PRINCIPAL, managerDN);
            props.put(Context.SECURITY_CREDENTIALS, getManagerPassword());
        }
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        props.put(Context.PROVIDER_URL, getServerUrl() + '/');

        DirContext ctx = new InitialDirContext(props);
        Attributes atts = ctx.getAttributes("");
        Attribute a = atts.get("defaultNamingContext");
        if (a != null) // this entry is available on Active Directory. See http://msdn2.microsoft.com/en-us/library/ms684291(VS.85).aspx
            return a.toString();

        a = atts.get("namingcontexts");
        if (a == null) {
            LOGGER.warning("namingcontexts attribute not found in root DSE of " + server);
            return null;
        }
        return a.get().toString();
    } catch (NamingException e) {
        LOGGER.log(Level.WARNING, "Failed to connect to LDAP to infer Root DN for " + server, e);
        return null;
    }
}

From source file:fedora.server.security.servletfilters.ldap.FilterLdap.java

private Hashtable getEnvironment(String userid, String password) {
    String m = FilterSetup.getFilterNameAbbrev(FILTER_NAME) + " getEnvironment() ";
    Hashtable env = null;/* ww  w . j  a v  a  2s. c o m*/

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

        if (VERSION != null && !"".equals(VERSION)) {
            log.debug(m + "ldap explicit version==" + VERSION);
            env.put(CONTEXT_VERSION_KEY, VERSION);
        }
        log.debug(m + "ldap version==" + env.get(CONTEXT_VERSION_KEY));

        env.put(Context.PROVIDER_URL, URL);
        log.debug(m + "ldap url==" + env.get(Context.PROVIDER_URL));

        if (!bindRequired()) {
            log.debug(m + "\"binding\" anonymously");
        } else {
            env.put(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION);

            String userForBind = null;
            String passwordForBind = null;
            if (!individualUserBind()) {
                userForBind = SECURITY_PRINCIPAL;
                passwordForBind = SECURITY_CREDENTIALS;
                log.debug(m + "binding to protected directory");
            } else {
                passwordForBind = password;
                if (SECURITY_PRINCIPAL == null || "".equals(SECURITY_PRINCIPAL)) {
                    userForBind = userid;
                    log.debug(m + "binding for real user");
                } else {
                    //simulate test against user-bind at directory server
                    userForBind = SECURITY_PRINCIPAL;
                    log.debug(m + "binding for --test-- user");
                }
            }
            env.put(Context.SECURITY_CREDENTIALS, passwordForBind);
            String[] parms = { userForBind };
            String userFormattedForBind = applyFilter(BIND_FILTER, parms);
            env.put(Context.SECURITY_PRINCIPAL, userFormattedForBind);
        }
        log.debug(m + "bind w " + env.get(Context.SECURITY_AUTHENTICATION));
        log.debug(m + "user== " + env.get(Context.SECURITY_PRINCIPAL));
        log.debug(m + "passwd==" + env.get(Context.SECURITY_CREDENTIALS));
    } catch (Throwable th) {
        if (LOG_STACK_TRACES) {
            log.error(m + "couldn't set up env for DirContext", th);
        } else {
            log.error(m + "couldn't set up env for DirContext" + th.getMessage());
        }
    } finally {
        log.debug(m + "< " + env);
    }
    return env;
}

From source file:org.rhq.enterprise.server.resource.group.LdapGroupManagerBean.java

public Map<String, String> findLdapUserDetails(String userName) {
    Properties systemConfig = systemManager.getSystemConfiguration(subjectManager.getOverlord());
    HashMap<String, String> userDetails = new HashMap<String, String>();
    // Load our LDAP specific properties
    Properties env = getProperties(systemConfig);

    // Load the BaseDN
    String baseDN = (String) systemConfig.get(RHQConstants.LDAPBaseDN);

    // Load the LoginProperty
    String loginProperty = (String) systemConfig.get(RHQConstants.LDAPLoginProperty);
    if (loginProperty == null) {
        // Use the default
        loginProperty = "cn";
    }/*from   w  w  w.j  ava 2s  .  c om*/
    // Load any information we may need to bind
    String bindDN = (String) systemConfig.get(RHQConstants.LDAPBindDN);
    String bindPW = (String) systemConfig.get(RHQConstants.LDAPBindPW);

    // Load any search filter
    String searchFilter = (String) systemConfig.get(RHQConstants.LDAPFilter);
    if (bindDN != null) {
        env.setProperty(Context.SECURITY_PRINCIPAL, bindDN);
        env.setProperty(Context.SECURITY_CREDENTIALS, bindPW);
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    }

    try {
        InitialLdapContext ctx = new InitialLdapContext(env, null);
        SearchControls searchControls = getSearchControls();

        // Add the search filter if specified.  This only allows for a single search filter.. i.e. foo=bar.
        String filter;
        if ((searchFilter != null) && (searchFilter.length() != 0)) {
            filter = "(&(" + loginProperty + "=" + userName + ")" + "(" + searchFilter + "))";
        } else {
            filter = "(" + loginProperty + "=" + userName + ")";
        }

        log.debug("Using LDAP filter [" + filter + "] to locate user details for " + userName);

        // Loop through each configured base DN.  It may be useful
        // in the future to allow for a filter to be configured for
        // each BaseDN, but for now the filter will apply to all.
        String[] baseDNs = baseDN.split(BASEDN_DELIMITER);
        for (int x = 0; x < baseDNs.length; x++) {
            NamingEnumeration<SearchResult> answer = ctx.search(baseDNs[x], filter, searchControls);
            if (!answer.hasMoreElements()) { //BZ:582471- ldap api bug change
                log.debug("User " + userName + " not found for BaseDN " + baseDNs[x]);
                // Nothing found for this DN, move to the next one if we have one.
                continue;
            }

            // We use the first match
            SearchResult si = answer.next();
            //generate the DN
            String userDN = null;
            try {
                userDN = si.getNameInNamespace();
            } catch (UnsupportedOperationException use) {
                userDN = si.getName();
                if (userDN.startsWith("\"")) {
                    userDN = userDN.substring(1, userDN.length());
                }
                if (userDN.endsWith("\"")) {
                    userDN = userDN.substring(0, userDN.length() - 1);
                }
                userDN = userDN + "," + baseDNs[x];
            }
            userDetails.put("dn", userDN);

            // Construct the UserDN
            NamingEnumeration<String> keys = si.getAttributes().getIDs();
            while (keys.hasMore()) {
                String key = keys.next();
                Attribute value = si.getAttributes().get(key);
                if ((value != null) && (value.get() != null)) {
                    userDetails.put(key, value.get().toString());
                }
            }
            return userDetails;
        }
        return userDetails;
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.openkm.principal.LdapPrincipalAdapter.java

/**
 * Create static LDAP configuration environment.
 *//*w  w w.  j  a  va 2  s. c  om*/
private static Hashtable<String, String> getEnvironment() {
    Hashtable<String, String> env = new Hashtable<String, String>();

    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.PROVIDER_URL, Config.PRINCIPAL_LDAP_SERVER);

    // Enable connection pooling
    // @see http://docs.oracle.com/javase/jndi/tutorial/ldap/connect/pool.html
    env.put("com.sun.jndi.ldap.connect.pool", "true");

    /**
     * Referral values: ignore, follow or throw.
     * 
     * @see http://docs.oracle.com/javase/jndi/tutorial/ldap/referral/jndi.html
     * @see http://java.sun.com/products/jndi/jndi-ldap-gl.html
     */
    if (!"".equals(Config.PRINCIPAL_LDAP_REFERRAL)) {
        env.put(Context.REFERRAL, Config.PRINCIPAL_LDAP_REFERRAL);
    }

    // Optional is some cases (Max OS/X)
    if (!Config.PRINCIPAL_LDAP_SECURITY_PRINCIPAL.equals("")) {
        env.put(Context.SECURITY_PRINCIPAL, Config.PRINCIPAL_LDAP_SECURITY_PRINCIPAL);
    }

    if (!Config.PRINCIPAL_LDAP_SECURITY_CREDENTIALS.equals("")) {
        env.put(Context.SECURITY_CREDENTIALS, Config.PRINCIPAL_LDAP_SECURITY_CREDENTIALS);
    }

    return env;
}

From source file:com.alfaariss.oa.util.idmapper.jndi.JNDIMapper.java

/**
 * Reads JNDI connection information from the configuration.
 * <br>/*from  w w w .ja v  a 2s  . c  o m*/
 * Creates an <code>Hashtable</code> containing the JNDI environment variables.
 * @param oConfigurationManager The configuration manager
 * @param eConfig the configuration section
 * @return <code>DirContext</code> that contains the JNDI connection
 * @throws OAException if configuration reading fails
 */
private Hashtable<String, String> readJNDIContext(IConfigurationManager oConfigurationManager, Element eConfig)
        throws OAException {
    Hashtable<String, String> htEnvironment = new Hashtable<String, String>(11);

    try {
        Element eSecurityPrincipal = oConfigurationManager.getSection(eConfig, "security_principal");
        if (eSecurityPrincipal == null) {
            _logger.error("No 'security_principal' section found in 'resource' configuration");
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sPrincipal = oConfigurationManager.getParam(eSecurityPrincipal, "dn");
        if (sPrincipal == null) {
            _logger.error("No item 'dn' item found in configuration");
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sPassword = oConfigurationManager.getParam(eSecurityPrincipal, "password");
        if (sPassword == null) {
            _logger.error("No 'password' item found in configuration ");
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sDriver = oConfigurationManager.getParam(eConfig, "driver");
        if (sDriver == null) {
            _logger.error("No 'driver' item found in configuration");
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }

        String sUrl = oConfigurationManager.getParam(eConfig, "url");
        if (sUrl == null) {
            _logger.error("No valid config item 'url' found in configuration");
            throw new OAException(SystemErrors.ERROR_CONFIG_READ);
        }

        if (sUrl.length() >= 5 && sUrl.substring(0, 5).equalsIgnoreCase("ldaps")) {
            // Request SSL transport
            htEnvironment.put(Context.SECURITY_PROTOCOL, "ssl");
            _logger.info("SSL enabled");
        } else {
            _logger.info("SSL disabled");
        }

        htEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, sDriver);
        htEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple");
        htEnvironment.put(Context.SECURITY_PRINCIPAL, sPrincipal);
        htEnvironment.put(Context.SECURITY_CREDENTIALS, sPassword);
        htEnvironment.put(Context.PROVIDER_URL, sUrl);
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.error("Could not create a connection", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
    return htEnvironment;
}

From source file:org.apache.hadoop.security.LdapGroupsMapping.java

DirContext getDirContext() throws NamingException {
    if (ctx == null) {
        // Set up the initial environment for LDAP connectivity
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, com.sun.jndi.ldap.LdapCtxFactory.class.getName());
        env.put(Context.PROVIDER_URL, ldapUrl);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");

        // Set up SSL security, if necessary
        if (useSsl) {
            env.put(Context.SECURITY_PROTOCOL, "ssl");
            System.setProperty("javax.net.ssl.keyStore", keystore);
            System.setProperty("javax.net.ssl.keyStorePassword", keystorePass);
        }// w  w w . ja  v a2  s  .  co  m

        env.put(Context.SECURITY_PRINCIPAL, bindUser);
        env.put(Context.SECURITY_CREDENTIALS, bindPassword);

        env.put("com.sun.jndi.ldap.connect.timeout",
                conf.get(CONNECTION_TIMEOUT, String.valueOf(CONNECTION_TIMEOUT_DEFAULT)));
        env.put("com.sun.jndi.ldap.read.timeout", conf.get(READ_TIMEOUT, String.valueOf(READ_TIMEOUT_DEFAULT)));

        ctx = new InitialDirContext(env);
    }

    return ctx;
}