Example usage for javax.naming.ldap InitialLdapContext InitialLdapContext

List of usage examples for javax.naming.ldap InitialLdapContext InitialLdapContext

Introduction

In this page you can find the example usage for javax.naming.ldap InitialLdapContext InitialLdapContext.

Prototype

@SuppressWarnings("unchecked")
public InitialLdapContext(Hashtable<?, ?> environment, Control[] connCtls) throws NamingException 

Source Link

Document

Constructs an initial context using environment properties and connection request controls.

Usage

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

/**
 * retrieve home directory of given user.
 *
 * @param inBenutzer/*  ww w .j  a v  a  2 s  .  co  m*/
 *            User object
 * @return path as string
 */
public String getUserHomeDirectory(User inBenutzer) {
    if (ConfigCore.getBooleanParameter("useLocalDirectory", false)) {
        return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin();
    }
    Hashtable<String, String> env = getLdapConnectionSettings();
    if (ConfigCore.getBooleanParameter("ldap_useTLS", false)) {

        env = new Hashtable<>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ConfigCore.getParameter("ldap_url"));
        env.put("java.naming.ldap.version", "3");
        LdapContext ctx = null;
        StartTlsResponse tls = null;
        try {
            ctx = new InitialLdapContext(env, null);

            // Authentication must be performed over a secure channel
            tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
            tls.negotiate();

            // Authenticate via SASL EXTERNAL mechanism using client X.509
            // certificate contained in JVM keystore
            ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));

            ctx.reconnect(null);

            Attributes attrs = ctx.getAttributes(getUserDN(inBenutzer));
            Attribute la = attrs.get("homeDirectory");
            return (String) la.get(0);

            // Perform search for privileged attributes under authenticated
            // context

        } catch (IOException e) {
            logger.error("TLS negotiation error:", e);

            return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin();
        } catch (NamingException e) {

            logger.error("JNDI error:", e);

            return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin();
        } finally {
            if (tls != null) {
                try {
                    // Tear down TLS connection
                    tls.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
            if (ctx != null) {
                try {
                    // Close LDAP connection
                    ctx.close();
                } catch (NamingException e) {
                    logger.error(e);
                }
            }
        }
    } else if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) {
        env.put(Context.SECURITY_AUTHENTICATION, "none");
    } else {
        env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
        env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));

    }
    DirContext ctx;
    String rueckgabe = "";
    try {
        ctx = new InitialDirContext(env);
        Attributes attrs = ctx.getAttributes(getUserDN(inBenutzer));
        Attribute la = attrs.get("homeDirectory");
        rueckgabe = (String) la.get(0);
        ctx.close();
    } catch (NamingException e) {
        logger.error(e);
    }
    return rueckgabe;
}

From source file:com.aurel.track.util.LdapUtil.java

/**
 * Gets the initial context/*from w  w  w .  j a  v  a 2  s.co  m*/
 * 
 * @param providerUrl
 * @param bindDN
 * @param bindPassword
 * @return
 */
public static LdapContext getInitialContext(String providerUrl, String bindDN, String bindPassword) {
    List<String> trace = new ArrayList<String>();
    LOGGER.debug("providerURL: " + providerUrl);
    trace.add("Attempting to connect to the LDAP server...");
    if (providerUrl != null && providerUrl.startsWith("ldaps:")) {
        System.setProperty("javax.net.ssl.trustStore", PATH_TO_KEY_STORE);
        trace.add("Using ldaps: with keystore at " + PATH_TO_KEY_STORE);
        File ks = new File(PATH_TO_KEY_STORE);
        if (!ks.exists()) {
            trace.add("*** There is no keystore at " + PATH_TO_KEY_STORE);
        }
    }
    if (providerUrl == null) {
        LOGGER.warn("LDAP provider URL should not be null.");
        return null;
    }
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    if (LOGGER.isDebugEnabled()) {
        env.put("com.sun.jndi.ldape.trace.ber", System.err);
    }
    env.put("java.naming.ldap.version", "3");
    env.put("com.sun.jndi.ldap.connect.timeout", "10000");
    env.put("com.sun.jndi.dns.timeout.initial", "2000");
    env.put("com.sun.jndi.dns.timeout.retries", "3");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, providerUrl);
    if ((bindDN != null) && !bindDN.equals("")) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, bindDN);
        env.put(Context.SECURITY_CREDENTIALS, bindPassword);
        LOGGER.debug("bind with bindDN:" + bindDN + " " + "bindPassword=" + bindPassword.replaceAll(".", "*"));
        trace.add("Preparing to bind to the LDAP server with DN = " + bindDN + " and password '****");
    } else {
        LOGGER.debug("bind anonymous");
        trace.add("Preparing to bind anonymously to the LDAP server");
    }
    try {
        return new InitialLdapContext(env, null);
    } catch (NamingException e) {
        for (String msg : trace) {
            LOGGER.error(msg);
        }
        LOGGER.error("Getting the initial ldap context failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        try {
            new InitialDirContext(env);
        } catch (NamingException e1) {
            LOGGER.error("Getting the initial dir context failed with " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
        return null;
    }
}

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);
    }//ww  w  .  j a  va 2s  . c o  m

    // 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.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 va 2  s  .  c om

    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: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./*from ww  w. ja v  a 2s.c  om*/
 *
 * @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:com.communote.server.test.ldap.AbstractApacheDSServer.java

/**
 * Sets the contexts of this class taking into account the extras and overrides properties.
 *
 * @param env//from  w  w  w  . j a  va 2 s. co  m
 *            an environment to use while setting up the system root.
 * @throws Exception
 *             if there is a failure of any kind
 */
protected void setContexts(Hashtable<String, Object> env) throws Exception {
    Hashtable<String, Object> envFinal = new Hashtable<String, Object>(env);
    envFinal.put(Context.PROVIDER_URL, ServerDNConstants.SYSTEM_DN);
    setSysRoot(new InitialLdapContext(envFinal, null));

    envFinal.put(Context.PROVIDER_URL, "");
    setRootDSE(getDirectoryService().getAdminSession());

    envFinal.put(Context.PROVIDER_URL, ServerDNConstants.OU_SCHEMA_DN);
    setSchemaRoot(new InitialLdapContext(envFinal, null));
}

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

protected InitialDirContext buildInitialDirContext(final Map<String, String> config, final int pageSize,
        final AuthenticationDiagnostic diagnostic) throws AuthenticationException {
    final AuthenticationDiagnostic effectiveDiagnostic = diagnostic != null ? diagnostic
            : new AuthenticationDiagnostic();

    final String securityPrincipal = config.get(Context.SECURITY_PRINCIPAL);
    final String providerURL = config.get(Context.PROVIDER_URL);

    if (this.isSSLSocketFactoryRequired(config)) {
        final KeyStore trustStore = this.initTrustStore();
        ThreadSafeSSLSocketFactory.initTrustedSSLSocketFactory(trustStore);
        config.put("java.naming.ldap.factory.socket", ThreadSafeSSLSocketFactory.class.getName());
    }/*w  w  w.  j a v  a  2  s  . c o m*/

    try {
        // If a page size has been requested, use LDAP v3 paging
        if (pageSize > 0) {
            final InitialLdapContext ctx = new InitialLdapContext(new Hashtable<>(config), null);
            ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.CRITICAL) });
            return ctx;
        } else {
            final InitialDirContext ret = new InitialDirContext(new Hashtable<>(config));
            final Object[] args = { providerURL, securityPrincipal };
            effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);
            return ret;
        }
    } catch (final javax.naming.AuthenticationException ax) {
        final Object[] args1 = { securityPrincipal };
        final Object[] args = { providerURL, securityPrincipal };
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_AUTHENTICATION, false, args1);

        // wrong user/password - if we get this far the connection is O.K
        final Object[] args2 = { securityPrincipal, ax.getLocalizedMessage() };
        throw new AuthenticationException("authentication.err.authentication", effectiveDiagnostic, args2, ax);
    } catch (final CommunicationException ce) {
        final Object[] args1 = { providerURL };
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args1);

        final StringBuffer message = new StringBuffer();

        message.append(ce.getClass().getName() + ", " + ce.getMessage());

        Throwable cause = ce.getCause();
        while (cause != null) {
            message.append(", ");
            message.append(cause.getClass().getName() + ", " + cause.getMessage());
            cause = cause.getCause();
        }

        // failed to connect
        final Object[] args = { providerURL, message.toString() };
        throw new AuthenticationException("authentication.err.communication", effectiveDiagnostic, args, ce);
    } catch (final NamingException nx) {
        final Object[] args = { providerURL };
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args);

        final StringBuffer message = new StringBuffer();

        message.append(nx.getClass().getName() + ", " + nx.getMessage());

        Throwable cause = nx.getCause();
        while (cause != null) {
            message.append(", ");
            message.append(cause.getClass().getName() + ", " + cause.getMessage());
            cause = cause.getCause();
        }

        // failed to connect
        final Object[] args1 = { providerURL, message.toString() };
        throw new AuthenticationException("authentication.err.connection", effectiveDiagnostic, args1, nx);
    } catch (final IOException e) {
        final Object[] args = { providerURL, securityPrincipal };
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);

        throw new AuthenticationException("Unable to encode LDAP v3 request controls", e);
    }
}

From source file:jp.ikedam.jenkins.plugins.ldap_sasl.LdapSaslSecurityRealm.java

/**
 * Authorize a user./*from w  w  w. j  a  va 2s .  c om*/
 * 
 * @param username
 * @param password
 * @see hudson.security.AbstractPasswordBasedSecurityRealm#authenticate(java.lang.String, java.lang.String)
 */
@Override
protected UserDetails authenticate(String username, String password) throws AuthenticationException {
    Logger logger = getLogger();

    // check configuration.
    String ldapUris = getValidLdapUris();
    if (StringUtils.isBlank(ldapUris)) {
        logger.severe("No valid LDAP URI is specified.");
        throw new AuthenticationServiceException("No valid LDAP URI is specified.");
    }

    String mechanisms = getMechanisms();
    if (StringUtils.isBlank(mechanisms)) {
        logger.severe("No valid mechanism is specified.");
        throw new AuthenticationServiceException("No valid mechanism is specified.");
    }

    // TODO: Test with LDAPS.

    // Parameters for JNDI
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapUris);
    env.put(Context.SECURITY_PRINCIPAL, username);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.SECURITY_AUTHENTICATION, mechanisms);
    env.put("com.sun.jndi.ldap.connect.timeout", Integer.toString(getConnectionTimeout()));
    env.put("com.sun.jndi.ldap.read.timeout", Integer.toString(getReadTimeout()));

    logger.fine("Authenticating with LDAP-SASL:");
    logger.fine(String.format("username=%s", username));
    logger.fine(String.format("servers=%s", ldapUris));
    logger.fine(String.format("mech=%s", mechanisms));

    LdapContext ctx = null;
    try {
        ctx = new InitialLdapContext(env, null);
    } catch (javax.naming.AuthenticationException e) {
        // Authentication Failure...
        throw new BadCredentialsException(String.format("Authentication failed: %s", username), e);
    } catch (NamingException e) {
        // Unexpected failure...
        throw new AuthenticationServiceException(String.format("Authentication failed: %s", username), e);
    }

    String userDn = (getUserDnResolver() != null) ? getUserDnResolver().getUserDn(ctx, username) : null;
    logger.fine(String.format("User DN is %s", userDn));

    List<GrantedAuthority> authorities = (getGroupResolver() != null)
            ? getGroupResolver().resolveGroup(ctx, userDn, username)
            : new ArrayList<GrantedAuthority>();

    logger.fine("Authenticating succeeded.");
    return new LdapUser(username, "", // password(not used)
            userDn, // dn of this user.
            true, // enabled
            true, // accountNonExpired
            true, // credentialsNonExpired
            true, // accountNonLocked
            authorities.toArray(new GrantedAuthority[0]));
}

From source file:com.adito.activedirectory.ActiveDirectoryUserDatabaseConfiguration.java

public InitialLdapContext getInitialContext(String url, Map<String, String> properties) throws NamingException {
    Hashtable<String, String> variables = new Hashtable<String, String>(properties);
    variables.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    variables.put(Context.PROVIDER_URL, url); // Must use fully qualified hostname

    if (isSslProtcolType()) {
        variables.put("java.naming.ldap.factory.socket", "com.adito.boot.CustomSSLSocketFactory");
        // Add the custom socket factory
    }//w  w w  . j a  v a 2  s .co m

    if (isFollowReferrals()) {
        variables.put(Context.REFERRAL, "follow");
    }

    variables.put("com.sun.jndi.ldap.connect.timeout", String.valueOf(getTimeout()));
    variables.put("java.naming.ldap.version", "3");
    variables.put("com.sun.jndi.ldap.connect.pool", "true");
    variables.put("javax.security.sasl.qop", "auth-conf,auth-int,auth");
    variables.put(Context.SECURITY_PROTOCOL, getProtocolType());

    InitialLdapContext context = new InitialLdapContext(variables, null);
    String usedUrl = (String) context.getEnvironment().get(Context.PROVIDER_URL);
    setLastContactedActiveDirectoryUrl(usedUrl);
    return context;
}

From source file:nl.nn.adapterframework.ldap.LdapFindMemberPipe.java

private boolean findMember(String host, int port, String dnSearchIn, boolean useSsl, String dnFind,
        boolean recursiveSearch) throws NamingException {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    String provUrl = retrieveUrl(host, port, dnSearchIn, useSsl);
    env.put(Context.PROVIDER_URL, provUrl);
    if (StringUtils.isNotEmpty(cf.getUsername())) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, cf.getUsername());
        env.put(Context.SECURITY_CREDENTIALS, cf.getPassword());
    } else {/*  w  w w  .j a  v  a2s  .  co m*/
        env.put(Context.SECURITY_AUTHENTICATION, "none");
    }
    DirContext ctx = null;
    try {
        try {
            ctx = new InitialDirContext(env);
        } catch (CommunicationException e) {
            log.info("Cannot create constructor for DirContext (" + e.getMessage()
                    + "], will try again with dummy SocketFactory");
            env.put("java.naming.ldap.factory.socket", DummySSLSocketFactory.class.getName());
            ctx = new InitialLdapContext(env, null);
        }
        Attribute attrs = ctx.getAttributes("").get("member");
        if (attrs != null) {
            boolean found = false;
            for (int i = 0; i < attrs.size() && !found; i++) {
                String dnFound = (String) attrs.get(i);
                if (dnFound.equalsIgnoreCase(dnFind)) {
                    found = true;
                } else {
                    if (recursiveSearch) {
                        found = findMember(host, port, dnFound, useSsl, dnFind, recursiveSearch);
                    }
                }
            }
            return found;
        }
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.warn("Exception closing DirContext", e);
            }
        }
    }
    return false;
}