Search in sources :

Example 46 with InitialLdapContext

use of javax.naming.ldap.InitialLdapContext in project ART-TIME by Artezio.

the class LdapClient method listDepartments.

public Set<String> listDepartments() {
    InitialLdapContext ctx = null;
    Filter filter = new Filter(settings.getLdapDepartmentFilter(), new Object[] {});
    Set<String> departments = new HashSet<>();
    try {
        ctx = initializeContext();
        SearchControls controls = makeSearchControls();
        controls.setReturningAttributes(new String[] { settings.getLdapDepartmentFilterDepartmentAttribute() });
        NamingEnumeration<SearchResult> answer = ctx.search(settings.getLdapUserContextDN(), filter.getExpression(), filter.getArgs(), controls);
        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            Attributes attrs = sr.getAttributes();
            String department = parseAttribute(attrs.get(settings.getLdapDepartmentFilterDepartmentAttribute()));
            departments.add(WordUtils.capitalizeFully(department, new char[] { '-', ' ' }));
        }
        answer.close();
    } catch (NamingException ex) {
        throw new RuntimeException("Error getting Departments ", ex);
    } finally {
        closeContext(ctx);
    }
    return departments;
}
Also used : InitialLdapContext(javax.naming.ldap.InitialLdapContext) Attributes(javax.naming.directory.Attributes) SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException)

Example 47 with InitialLdapContext

use of javax.naming.ldap.InitialLdapContext in project uavstack by uavorg.

the class GUISSOLdapClient method ldapApiCheck.

// ======================================init end========================================
// ======================================ldap api begin========================================
private boolean ldapApiCheck(String loginId, String password) {
    boolean result = false;
    String action = "login";
    LdapContext newContext = null;
    try {
        initLdapContext(action);
        Properties actionParam = ldapParams.get(action);
        // 替换参数,账号密码验证
        actionParam.put(Context.SECURITY_PRINCIPAL, loginId);
        actionParam.put(Context.SECURITY_CREDENTIALS, password);
        // 密码验证,不报错则为验证成功
        newContext = new InitialLdapContext(actionParam, null);
        result = true;
        loggerInfo("LDAP信息", "登陆校验", "成功", loginId);
    } catch (AuthenticationException e) {
        // 此异常为用户验证失败
        loggerInfo("LDAP信息", "登陆校验", "失败", loginId);
    } catch (Exception e1) {
        loggerError("LDAP信息校验", loginId, e1);
        clearLdapContext(action);
    } finally {
        try {
            if (null != newContext) {
                newContext.close();
            }
        } catch (NamingException e) {
            loggerError("LDAP信息校验,链接关闭", loginId, e);
        }
    }
    return result;
}
Also used : AuthenticationException(javax.naming.AuthenticationException) InitialLdapContext(javax.naming.ldap.InitialLdapContext) NamingException(javax.naming.NamingException) Properties(java.util.Properties) InitialLdapContext(javax.naming.ldap.InitialLdapContext) LdapContext(javax.naming.ldap.LdapContext) ApphubException(com.creditease.uav.exception.ApphubException) NamingException(javax.naming.NamingException) AuthenticationException(javax.naming.AuthenticationException)

Example 48 with InitialLdapContext

use of javax.naming.ldap.InitialLdapContext in project iaf by ibissource.

the class LoginFilter method checkUsernamePassword.

private boolean checkUsernamePassword(String username, String password, String authorizePathMode) {
    String dnUser = Misc.replace(ldapAuthUserBase, "%UID%", username);
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapAuthUrl);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, dnUser);
    env.put(Context.SECURITY_CREDENTIALS, password);
    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);
        }
        if (authorizePathMode == null) {
            return true;
        } else {
            if (authorizePathMode.equals(AUTH_PATH_MODE_OBSERVER)) {
                if (isMemberOf(ctx, dnUser, ldapAuthObserverBase)) {
                    return true;
                }
                if (isMemberOf(ctx, dnUser, ldapAuthDataAdminBase)) {
                    return true;
                }
            }
            if (authorizePathMode.equals(AUTH_PATH_MODE_DATAADMIN)) {
                if (isMemberOf(ctx, dnUser, ldapAuthDataAdminBase)) {
                    return true;
                }
            }
            if (authorizePathMode.equals(AUTH_PATH_MODE_TESTER)) {
                if (isMemberOf(ctx, dnUser, ldapAuthTesterBase)) {
                    return true;
                }
            }
        }
    } catch (AuthenticationException e) {
        return false;
    } catch (Exception e) {
        log.warn("LoginFilter caught Exception", e);
        return false;
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                log.warn("LoginFilter caught Exception", e);
            }
        }
    }
    return false;
}
Also used : CommunicationException(javax.naming.CommunicationException) AuthenticationException(javax.naming.AuthenticationException) Hashtable(java.util.Hashtable) InitialLdapContext(javax.naming.ldap.InitialLdapContext) InitialDirContext(javax.naming.directory.InitialDirContext) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) ServletException(javax.servlet.ServletException) NamingException(javax.naming.NamingException) AuthenticationException(javax.naming.AuthenticationException) IOException(java.io.IOException) CommunicationException(javax.naming.CommunicationException)

Example 49 with InitialLdapContext

use of javax.naming.ldap.InitialLdapContext in project keycloak by keycloak.

the class LDAPContextManager method createLdapContext.

private void createLdapContext() throws NamingException {
    Hashtable<Object, Object> connProp = getConnectionProperties(ldapConfig);
    if (!LDAPConstants.AUTH_TYPE_NONE.equals(ldapConfig.getAuthType())) {
        vaultCharSecret = getVaultSecret();
        if (vaultCharSecret != null && !ldapConfig.isStartTls()) {
            connProp.put(SECURITY_CREDENTIALS, vaultCharSecret.getAsArray().orElse(ldapConfig.getBindCredential().toCharArray()));
        }
    }
    ldapContext = new InitialLdapContext(connProp, null);
    if (ldapConfig.isStartTls()) {
        SSLSocketFactory sslSocketFactory = null;
        String useTruststoreSpi = ldapConfig.getUseTruststoreSpi();
        if (useTruststoreSpi != null && useTruststoreSpi.equals(LDAPConstants.USE_TRUSTSTORE_ALWAYS)) {
            TruststoreProvider provider = session.getProvider(TruststoreProvider.class);
            sslSocketFactory = provider.getSSLSocketFactory();
        }
        tlsResponse = startTLS(ldapContext, ldapConfig.getAuthType(), ldapConfig.getBindDN(), vaultCharSecret.getAsArray().orElse(ldapConfig.getBindCredential().toCharArray()), sslSocketFactory);
        // Exception should be already thrown by LDAPContextManager.startTLS if "startTLS" could not be established, but rather do some additional check
        if (tlsResponse == null) {
            throw new NamingException("Wasn't able to establish LDAP connection through StartTLS");
        }
    }
}
Also used : InitialLdapContext(javax.naming.ldap.InitialLdapContext) NamingException(javax.naming.NamingException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) TruststoreProvider(org.keycloak.truststore.TruststoreProvider)

Example 50 with InitialLdapContext

use of javax.naming.ldap.InitialLdapContext in project scheduling by ow2-proactive.

the class LDAPLoginModule method createLdapContext.

private ContextHandler createLdapContext(String user, String password, boolean requireAuthentication) {
    LdapContext ctx = null;
    StartTlsResponse tls = null;
    Hashtable<String, String> env = createBasicEnvForInitalContext();
    try {
        if (!START_TLS) {
            if (requireAuthentication || !AUTHENTICATION_METHOD.equals(ANONYMOUS_LDAP_CONNECTION)) {
                if (requireAuthentication) {
                    // In case of anonymous bind, when we need to check some user credentials, we must force authentication to be simple
                    env.put(Context.SECURITY_AUTHENTICATION, ANONYMOUS_LDAP_CONNECTION.equals(AUTHENTICATION_METHOD) ? "simple" : AUTHENTICATION_METHOD);
                } else {
                    env.put(Context.SECURITY_AUTHENTICATION, AUTHENTICATION_METHOD);
                }
                env.put(Context.SECURITY_PRINCIPAL, user);
                env.put(Context.SECURITY_CREDENTIALS, password);
            }
        }
        // Create the initial directory context
        ctx = new InitialLdapContext(env, null);
        if (START_TLS) {
            // Start TLS
            tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
            if (ANY_HOSTNAME) {
                tls.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            }
            if (ANY_CERTIFICATE) {
                SSLContext context = SSLContext.getInstance("TLS");
                context.init(null, new X509TrustManager[] { new X509TrustManager() {

                    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[0];
                    }
                } }, new SecureRandom());
                tls.negotiate(context.getSocketFactory());
            } else {
                tls.negotiate();
            }
            if (requireAuthentication || !AUTHENTICATION_METHOD.equals(ANONYMOUS_LDAP_CONNECTION)) {
                if (requireAuthentication) {
                    // In case of anonymous bind, when we need to check some user credentials, we must force authentication to be simple
                    ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, ANONYMOUS_LDAP_CONNECTION.equals(AUTHENTICATION_METHOD) ? "simple" : AUTHENTICATION_METHOD);
                } else {
                    ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, AUTHENTICATION_METHOD);
                }
                ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, user);
                ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
            }
        }
        return new ContextHandler(ctx, tls);
    } catch (NamingException e) {
        logger.error("Problem checking user password, user password may be wrong: " + e);
        return null;
    } catch (Exception e) {
        logger.error("Problem when creating the ldap context", e);
        return null;
    }
}
Also used : SecureRandom(java.security.SecureRandom) CertificateException(java.security.cert.CertificateException) SSLContext(javax.net.ssl.SSLContext) X509Certificate(java.security.cert.X509Certificate) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) NamingException(javax.naming.NamingException) FailedLoginException(javax.security.auth.login.FailedLoginException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) StartTlsResponse(javax.naming.ldap.StartTlsResponse) X509TrustManager(javax.net.ssl.X509TrustManager) InitialLdapContext(javax.naming.ldap.InitialLdapContext) NamingException(javax.naming.NamingException) StartTlsRequest(javax.naming.ldap.StartTlsRequest) InitialLdapContext(javax.naming.ldap.InitialLdapContext) LdapContext(javax.naming.ldap.LdapContext)

Aggregations

InitialLdapContext (javax.naming.ldap.InitialLdapContext)54 NamingException (javax.naming.NamingException)30 Hashtable (java.util.Hashtable)17 LdapContext (javax.naming.ldap.LdapContext)17 Attributes (javax.naming.directory.Attributes)16 Properties (java.util.Properties)14 SearchResult (javax.naming.directory.SearchResult)14 IOException (java.io.IOException)11 AuthenticationException (javax.naming.AuthenticationException)10 NamingEnumeration (javax.naming.NamingEnumeration)10 StartTlsRequest (javax.naming.ldap.StartTlsRequest)10 BasicAttributes (javax.naming.directory.BasicAttributes)9 Attribute (javax.naming.directory.Attribute)8 SearchControls (javax.naming.directory.SearchControls)8 LdapConfigProperties (org.bedework.calfacade.configs.LdapConfigProperties)7 CalFacadeException (org.bedework.calfacade.exc.CalFacadeException)7 StartTlsResponse (javax.naming.ldap.StartTlsResponse)6 CommunicationException (javax.naming.CommunicationException)5 DirContext (javax.naming.directory.DirContext)5 BwGroup (org.bedework.calfacade.BwGroup)5