Example usage for javax.naming Context INITIAL_CONTEXT_FACTORY

List of usage examples for javax.naming Context INITIAL_CONTEXT_FACTORY

Introduction

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

Prototype

String INITIAL_CONTEXT_FACTORY

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

Click Source Link

Document

Constant that holds the name of the environment property for specifying the initial context factory to use.

Usage

From source file:io.apiman.gateway.engine.policies.BasicAuthenticationPolicyTest.java

/**
 * Test method for {@link io.apiman.gateway.engine.policies.BasicAuthenticationPolicy#apply(ServiceRequest, IPolicyContext, Object, IPolicyChain)}.
 *//*from  w ww  . j a va  2  s  .  co  m*/
@Test
public void testApplyJdbc() throws Exception {
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, InitialContextFactoryForTest.class.getName());

    // Create a test datasource and bind it to JNDI
    BasicDataSource ds = createInMemoryDatasource();
    InitialContext ctx = new InitialContext();
    ensureCtx(ctx, "java:comp/env"); //$NON-NLS-1$
    ensureCtx(ctx, "java:comp/env/jdbc"); //$NON-NLS-1$
    ctx.bind("java:comp/env/jdbc/TestAuthDS", ds); //$NON-NLS-1$

    // A live LDAP server is required to run this test!
    BasicAuthenticationPolicy policy = new BasicAuthenticationPolicy();
    String json = "{\r\n" + "    \"realm\" : \"TestRealm\",\r\n"
            + "    \"forwardIdentityHttpHeader\" : \"X-Authenticated-Identity\",\r\n"
            + "    \"jdbcIdentity\" : {\r\n" + "        \"datasourcePath\" : \"jdbc/TestAuthDS\",\r\n"
            + "        \"query\" : \"SELECT * FROM users WHERE username = ? AND password = ?\",\r\n"
            + "        \"hashAlgorithm\" : \"SHA1\"\r\n" + "    }\r\n" + "}";
    Object config = policy.parseConfiguration(json);
    ServiceRequest request = new ServiceRequest();
    request.setType("GET");
    request.setApiKey("12345");
    request.setRemoteAddr("1.2.3.4");
    request.setDestination("/");
    IPolicyContext context = Mockito.mock(IPolicyContext.class);
    final PolicyFailure failure = new PolicyFailure();
    Mockito.when(context.getComponent(IPolicyFailureFactoryComponent.class))
            .thenReturn(new IPolicyFailureFactoryComponent() {
                @Override
                public PolicyFailure createFailure(PolicyFailureType type, int failureCode, String message) {
                    return failure;
                }
            });
    IPolicyChain<ServiceRequest> chain = Mockito.mock(IPolicyChain.class);

    // Failure
    policy.apply(request, context, config, chain);
    Mockito.verify(chain).doFailure(failure);

    // Failure
    request.getHeaders().put("Authorization", createBasicAuthorization(JDBC_USER, "invalid_password"));
    chain = Mockito.mock(IPolicyChain.class);
    policy.apply(request, context, config, chain);
    Mockito.verify(chain).doFailure(failure);

    // Success
    request.getHeaders().put("Authorization", createBasicAuthorization(JDBC_USER, JDBC_PASSWORD));
    chain = Mockito.mock(IPolicyChain.class);
    policy.apply(request, context, config, chain);
    Mockito.verify(chain).doApply(request);
}

From source file:org.apache.directory.server.ldap.handlers.sasl.AbstractSaslCallbackHandler.java

/**
 * Convenience method for getting an environment suitable for acquiring
 * an {@link LdapContext} for the client.
 * //from   w w w. j a va2  s. c o  m
 * @param session The current session.
 * @return An environment suitable for acquiring an {@link LdapContext} for the client.
 */
protected Hashtable<String, Object> getEnvironment(IoSession session) {
    Hashtable<String, Object> env = new Hashtable<>();
    env.put(Context.PROVIDER_URL, session.getAttribute("baseDn"));
    env.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.directory.server.core.jndi.CoreContextFactory");
    env.put(Context.SECURITY_PRINCIPAL, ServerDNConstants.ADMIN_SYSTEM_DN);
    env.put(Context.SECURITY_CREDENTIALS, "secret");
    env.put(Context.SECURITY_AUTHENTICATION, AuthenticationLevel.SIMPLE.toString());

    return env;
}

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  w w.  j  a v  a  2s  .  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);
    }
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Returns <i>true</i> if the Active Directory account and password are
 * valid (e.g. a context can be successfully established) or <i>false</i>
 * otherwise./*w w  w  . jav  a2 s .c o m*/
 *
 * @param anAccountName An Active Directory account name.
 * @param anAccountPassword An Active Directory account passowrd.
 *
 * @return <i>true</i> or <i>false</i>
 */
@SuppressWarnings("unchecked")
public boolean isAccountValid(String anAccountName, String anAccountPassword) {
    boolean isValid = false;
    Logger appLogger = mAppMgr.getLogger(this, "isAccountValid");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    DataBag userBag = schemaUserBag();
    userBag.setValueByName(LDAP_ACCOUNT_NAME, anAccountName);

    try {
        loadUserByAccountName(userBag);
        Hashtable<String, String> environmentalVariables = new Hashtable<String, String>();
        environmentalVariables.put("com.sun.jndi.ldap.connect.pool", StrUtl.STRING_TRUE);
        environmentalVariables.put(Context.PROVIDER_URL, getPropertyValue("domain_url", null));
        environmentalVariables.put("java.naming.ldap.attributes.binary", "tokenGroups objectSid");
        environmentalVariables.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        environmentalVariables.put(Context.SECURITY_PRINCIPAL,
                userBag.getValueAsString(LDAP_DISTINGUISHED_NAME));
        environmentalVariables.put(Context.SECURITY_CREDENTIALS, anAccountPassword);
        environmentalVariables.put(Context.REFERRAL, getPropertyValue("referral_handling", "ignore"));
        environmentalVariables.put(Context.SECURITY_AUTHENTICATION,
                getPropertyValue("authentication", "simple"));

        LdapContext ldapContext = new InitialLdapContext(environmentalVariables, null);
        ldapContext.close();

        isValid = true;
    } catch (Exception ignored) {
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);

    return isValid;
}

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

/**
 * //from w ww.j  a v  a2  s. c o  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.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 w w w. jav  a2 s . c  o  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: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();/*from  ww  w  .  j  ava 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:eu.uqasar.util.ldap.LdapManager.java

private LdapContext getConnection(LdapSettings settings, final String userName, final String password)
        throws CommunicationException, NamingException {
    Validate.notEmpty(settings.getAuthUserDN());

    // bind by using the specified username/password
    Properties props = new Properties();
    props.put(Context.SECURITY_PRINCIPAL, userName == null ? settings.getAuthUserDN() : userName);
    if (settings.getAuthUserPassword() != null || password != null) {
        props.put(Context.SECURITY_CREDENTIALS, password == null ? settings.getAuthUserPassword() : password);
    }//from  w  ww . j  ava 2 s  .com

    // ensures that objectSID attribute values
    // will be returned as a byte[] instead of a String
    props.put("java.naming.ldap.attributes.binary", "objectSID");

    // the following is helpful in debugging errors
    // props.put("com.sun.jndi.ldap.trace.ber", System.err);
    String ldapURL = String.format("ldap://%s:%s", settings.getHost(), settings.getPort());
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    props.put(Context.PROVIDER_URL, ldapURL);
    props.put(Context.REFERRAL, "follow");
    try {
        return new InitialLdapContext(props, null);
    } catch (CommunicationException e) {
        logger.warn(String.format("Failed to connect to %s:%s", settings.getHost(), settings.getPort()), e);
        throw e;
    } catch (NamingException e) {
        logger.warn(String.format("Failed to authenticate %s:%s", settings.getHost(), settings.getPort()), e);
        throw e;
    }
}

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

/**
 * Create static LDAP configuration environment.
 *///from w  ww . j a  v  a2s  .  c o m
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:org.settings4j.connector.JNDIConnectorTest.java

public static void setTomcatJNDIContextProperties() {
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
    System.setProperty(Context.PROVIDER_URL, "localhost:1099");
    System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");

}