Search in sources :

Example 1 with SearchConnectionValidator

use of org.ldaptive.SearchConnectionValidator in project cas by apereo.

the class LdapUtils method newLdaptivePooledConnectionFactory.

/**
 * New pooled connection factory pooled connection factory.
 *
 * @param l the ldap properties
 * @return the pooled connection factory
 */
public static PooledConnectionFactory newLdaptivePooledConnectionFactory(final AbstractLdapProperties l) {
    val cc = newLdaptiveConnectionConfig(l);
    LOGGER.debug("Creating LDAP connection pool configuration for [{}]", l.getLdapUrl());
    val pooledCf = new PooledConnectionFactory(cc);
    pooledCf.setMinPoolSize(l.getMinPoolSize());
    pooledCf.setMaxPoolSize(l.getMaxPoolSize());
    pooledCf.setValidateOnCheckOut(l.isValidateOnCheckout());
    pooledCf.setValidatePeriodically(l.isValidatePeriodically());
    pooledCf.setBlockWaitTime(Beans.newDuration(l.getBlockWaitTime()));
    val strategy = new IdlePruneStrategy();
    strategy.setIdleTime(Beans.newDuration(l.getIdleTime()));
    strategy.setPrunePeriod(Beans.newDuration(l.getPrunePeriod()));
    pooledCf.setPruneStrategy(strategy);
    val validator = l.getValidator();
    switch(validator.getType().trim().toLowerCase()) {
        case "compare":
            val compareRequest = new CompareRequest(validator.getDn(), validator.getAttributeName(), validator.getAttributeValue());
            val compareValidator = new CompareConnectionValidator(compareRequest);
            compareValidator.setValidatePeriod(Beans.newDuration(l.getValidatePeriod()));
            compareValidator.setValidateTimeout(Beans.newDuration(l.getValidateTimeout()));
            pooledCf.setValidator(compareValidator);
            break;
        case "none":
            LOGGER.debug("No validator is configured for the LDAP connection pool of [{}]", l.getLdapUrl());
            break;
        case "search":
        default:
            val searchRequest = new SearchRequest();
            searchRequest.setBaseDn(validator.getBaseDn());
            searchRequest.setFilter(validator.getSearchFilter());
            searchRequest.setReturnAttributes(ReturnAttributes.NONE.value());
            searchRequest.setSearchScope(SearchScope.valueOf(validator.getScope()));
            searchRequest.setSizeLimit(1);
            val searchValidator = new SearchConnectionValidator(searchRequest);
            searchValidator.setValidatePeriod(Beans.newDuration(l.getValidatePeriod()));
            searchValidator.setValidateTimeout(Beans.newDuration(l.getValidateTimeout()));
            pooledCf.setValidator(searchValidator);
            break;
    }
    pooledCf.setFailFastInitialize(l.isFailFast());
    if (StringUtils.isNotBlank(l.getPoolPassivator())) {
        val pass = AbstractLdapProperties.LdapConnectionPoolPassivator.valueOf(l.getPoolPassivator().toUpperCase());
        switch(pass) {
            case BIND:
                if (StringUtils.isNotBlank(l.getBindDn()) && StringUtils.isNoneBlank(l.getBindCredential())) {
                    val bindRequest = new SimpleBindRequest(l.getBindDn(), l.getBindCredential());
                    pooledCf.setPassivator(new BindConnectionPassivator(bindRequest));
                    LOGGER.debug("Created [{}] passivator for [{}]", l.getPoolPassivator(), l.getLdapUrl());
                } else {
                    val values = Arrays.stream(AbstractLdapProperties.LdapConnectionPoolPassivator.values()).filter(v -> v != AbstractLdapProperties.LdapConnectionPoolPassivator.BIND).collect(Collectors.toList());
                    LOGGER.warn("[{}] pool passivator could not be created for [{}] given bind credentials are not specified. " + "If you are dealing with LDAP in such a way that does not require bind credentials, you may need to " + "set the pool passivator setting to one of [{}]", l.getPoolPassivator(), l.getLdapUrl(), values);
                }
                break;
            default:
                break;
        }
    }
    LOGGER.debug("Initializing ldap connection pool for [{}] and bindDn [{}]", l.getLdapUrl(), l.getBindDn());
    pooledCf.initialize();
    return pooledCf;
}
Also used : lombok.val(lombok.val) Arrays(java.util.Arrays) ConnectionFactory(org.ldaptive.ConnectionFactory) AllowAnyTrustManager(org.ldaptive.ssl.AllowAnyTrustManager) SearchOperation(org.ldaptive.SearchOperation) SearchResponse(org.ldaptive.SearchResponse) GroovyPasswordPolicyHandlingStrategy(org.apereo.cas.authentication.support.password.GroovyPasswordPolicyHandlingStrategy) AddRequest(org.ldaptive.AddRequest) AuthenticationPasswordPolicyHandlingStrategy(org.apereo.cas.authentication.AuthenticationPasswordPolicyHandlingStrategy) DnResolver(org.ldaptive.auth.DnResolver) StringUtils(org.apache.commons.lang3.StringUtils) DefaultLdapAccountStateHandler(org.apereo.cas.authentication.support.DefaultLdapAccountStateHandler) ActivePassiveConnectionStrategy(org.ldaptive.ActivePassiveConnectionStrategy) AllowAnyHostnameVerifier(org.ldaptive.ssl.AllowAnyHostnameVerifier) FormatDnResolver(org.ldaptive.auth.FormatDnResolver) CompareConnectionValidator(org.ldaptive.CompareConnectionValidator) Map(java.util.Map) AbstractLdapAuthenticationProperties(org.apereo.cas.configuration.model.support.ldap.AbstractLdapAuthenticationProperties) FreeIPAAuthenticationResponseHandler(org.ldaptive.auth.ext.FreeIPAAuthenticationResponseHandler) ApplicationContextProvider(org.apereo.cas.util.spring.ApplicationContextProvider) SimpleBindAuthenticationHandler(org.ldaptive.auth.SimpleBindAuthenticationHandler) CompareAuthenticationHandler(org.ldaptive.auth.CompareAuthenticationHandler) ConnectionConfig(org.ldaptive.ConnectionConfig) Unchecked(org.jooq.lambda.Unchecked) SaslConfig(org.ldaptive.sasl.SaslConfig) BindConnectionInitializer(org.ldaptive.BindConnectionInitializer) ModifyRequest(org.ldaptive.ModifyRequest) PagedResultsClient(org.ldaptive.control.util.PagedResultsClient) Set(java.util.Set) DnsSrvConnectionStrategy(org.ldaptive.DnsSrvConnectionStrategy) SearchScope(org.ldaptive.SearchScope) StandardCharsets(java.nio.charset.StandardCharsets) Slf4j(lombok.extern.slf4j.Slf4j) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException) FilterTemplate(org.ldaptive.FilterTemplate) AddOperation(org.ldaptive.AddOperation) LdapAttribute(org.ldaptive.LdapAttribute) DisposableBean(org.springframework.beans.factory.DisposableBean) LdapEntry(org.ldaptive.LdapEntry) ObjectGuidHandler(org.ldaptive.ad.handler.ObjectGuidHandler) RangeEntryHandler(org.ldaptive.ad.handler.RangeEntryHandler) User(org.ldaptive.auth.User) ActiveDirectoryLdapEntryHandler(org.apereo.services.persondir.support.ldap.ActiveDirectoryLdapEntryHandler) SearchEntryResolver(org.ldaptive.auth.SearchEntryResolver) ArrayList(java.util.ArrayList) UtilityClass(lombok.experimental.UtilityClass) LinkedHashMap(java.util.LinkedHashMap) SearchDnResolver(org.ldaptive.auth.SearchDnResolver) IdlePruneStrategy(org.ldaptive.pool.IdlePruneStrategy) ModifyOperation(org.ldaptive.ModifyOperation) ActiveDirectoryAuthenticationResponseHandler(org.ldaptive.auth.ext.ActiveDirectoryAuthenticationResponseHandler) FollowSearchReferralHandler(org.ldaptive.referral.FollowSearchReferralHandler) CompareRequest(org.ldaptive.CompareRequest) ServicesManager(org.apereo.cas.services.ServicesManager) MergeResultHandler(org.ldaptive.handler.MergeResultHandler) lombok.val(lombok.val) AttributeModification(org.ldaptive.AttributeModification) SearchRequest(org.ldaptive.SearchRequest) DefaultConnectionFactory(org.ldaptive.DefaultConnectionFactory) RoundRobinConnectionStrategy(org.ldaptive.RoundRobinConnectionStrategy) Mechanism(org.ldaptive.sasl.Mechanism) CaseChangeEntryHandler(org.ldaptive.handler.CaseChangeEntryHandler) PasswordExpirationAuthenticationResponseHandler(org.ldaptive.auth.ext.PasswordExpirationAuthenticationResponseHandler) AuthenticationHandlerResponse(org.ldaptive.auth.AuthenticationHandlerResponse) FastBindConnectionInitializer(org.ldaptive.ad.extended.FastBindConnectionInitializer) KeyStoreCredentialConfig(org.ldaptive.ssl.KeyStoreCredentialConfig) LdapException(org.ldaptive.LdapException) PooledConnectionFactory(org.ldaptive.PooledConnectionFactory) LdapAuthenticationHandler(org.apereo.cas.authentication.LdapAuthenticationHandler) SimpleBindRequest(org.ldaptive.SimpleBindRequest) SetFactoryBean(org.springframework.beans.factory.config.SetFactoryBean) SneakyThrows(lombok.SneakyThrows) UnicodePwdAttribute(org.ldaptive.ad.UnicodePwdAttribute) URL(java.net.URL) RequiredArgsConstructor(lombok.RequiredArgsConstructor) PasswordPolicyContext(org.apereo.cas.authentication.support.password.PasswordPolicyContext) PasswordPolicyAuthenticationRequestHandler(org.ldaptive.auth.ext.PasswordPolicyAuthenticationRequestHandler) Beans(org.apereo.cas.configuration.support.Beans) DerefAliases(org.ldaptive.DerefAliases) FunctionUtils(org.apereo.cas.util.function.FunctionUtils) PrincipalFactory(org.apereo.cas.authentication.principal.PrincipalFactory) ScriptResourceCacheManager(org.apereo.cas.util.scripting.ScriptResourceCacheManager) PasswordModifyRequest(org.ldaptive.extended.PasswordModifyRequest) URI(java.net.URI) DeleteRequest(org.ldaptive.DeleteRequest) SslConfig(org.ldaptive.ssl.SslConfig) PrimaryGroupIdHandler(org.ldaptive.ad.handler.PrimaryGroupIdHandler) X509CredentialConfig(org.ldaptive.ssl.X509CredentialConfig) AbstractLdapProperties(org.apereo.cas.configuration.model.support.ldap.AbstractLdapProperties) DefaultHostnameVerifier(org.ldaptive.ssl.DefaultHostnameVerifier) Collectors(java.util.stream.Collectors) LdapAuthenticationProperties(org.apereo.cas.configuration.model.support.ldap.LdapAuthenticationProperties) Objects(java.util.Objects) DnAttributeEntryHandler(org.ldaptive.handler.DnAttributeEntryHandler) List(java.util.List) DeleteOperation(org.ldaptive.DeleteOperation) SearchResultHandler(org.ldaptive.handler.SearchResultHandler) LdapPasswordPolicyProperties(org.apereo.cas.configuration.model.support.ldap.LdapPasswordPolicyProperties) AuthenticationRequestHandler(org.ldaptive.auth.AuthenticationRequestHandler) CoreAuthenticationUtils(org.apereo.cas.authentication.CoreAuthenticationUtils) EDirectoryAuthenticationResponseHandler(org.ldaptive.auth.ext.EDirectoryAuthenticationResponseHandler) IntStream(java.util.stream.IntStream) PasswordEncoderUtils(org.apereo.cas.authentication.support.password.PasswordEncoderUtils) ReturnAttributes(org.ldaptive.ReturnAttributes) AuthenticationResponse(org.ldaptive.auth.AuthenticationResponse) BindConnectionPassivator(org.ldaptive.pool.BindConnectionPassivator) AuthenticationCriteria(org.ldaptive.auth.AuthenticationCriteria) OptionalWarningLdapAccountStateHandler(org.apereo.cas.authentication.support.OptionalWarningLdapAccountStateHandler) ArrayUtils(org.apache.commons.lang3.ArrayUtils) Multimap(com.google.common.collect.Multimap) AuthenticationHandler(org.ldaptive.auth.AuthenticationHandler) HashSet(java.util.HashSet) EntryResolver(org.ldaptive.auth.EntryResolver) QualityOfProtection(org.ldaptive.sasl.QualityOfProtection) AuthenticationResponseHandler(org.ldaptive.auth.AuthenticationResponseHandler) Period(java.time.Period) PasswordPolicyAuthenticationResponseHandler(org.ldaptive.auth.ext.PasswordPolicyAuthenticationResponseHandler) RandomConnectionStrategy(org.ldaptive.RandomConnectionStrategy) ObjectSidHandler(org.ldaptive.ad.handler.ObjectSidHandler) RejectResultCodeLdapPasswordPolicyHandlingStrategy(org.apereo.cas.authentication.support.RejectResultCodeLdapPasswordPolicyHandlingStrategy) ResultCode(org.ldaptive.ResultCode) WatchableGroovyScriptResource(org.apereo.cas.util.scripting.WatchableGroovyScriptResource) SearchConnectionValidator(org.ldaptive.SearchConnectionValidator) ApplicationContext(org.springframework.context.ApplicationContext) DefaultTrustManager(org.ldaptive.ssl.DefaultTrustManager) Authenticator(org.ldaptive.auth.Authenticator) Credential(org.ldaptive.Credential) MergeAttributeEntryHandler(org.ldaptive.handler.MergeAttributeEntryHandler) LdapSearchEntryHandlersProperties(org.apereo.cas.configuration.model.support.ldap.LdapSearchEntryHandlersProperties) SecurityStrength(org.ldaptive.sasl.SecurityStrength) PrincipalNameTransformerUtils(org.apereo.cas.authentication.principal.PrincipalNameTransformerUtils) DefaultPasswordPolicyHandlingStrategy(org.apereo.cas.authentication.support.password.DefaultPasswordPolicyHandlingStrategy) RecursiveResultHandler(org.ldaptive.handler.RecursiveResultHandler) ExtendedOperation(org.ldaptive.extended.ExtendedOperation) LdapEntryHandler(org.ldaptive.handler.LdapEntryHandler) ExecutableCompiledGroovyScript(org.apereo.cas.util.scripting.ExecutableCompiledGroovyScript) IdlePruneStrategy(org.ldaptive.pool.IdlePruneStrategy) SearchRequest(org.ldaptive.SearchRequest) SearchConnectionValidator(org.ldaptive.SearchConnectionValidator) CompareRequest(org.ldaptive.CompareRequest) SimpleBindRequest(org.ldaptive.SimpleBindRequest) CompareConnectionValidator(org.ldaptive.CompareConnectionValidator) BindConnectionPassivator(org.ldaptive.pool.BindConnectionPassivator) PooledConnectionFactory(org.ldaptive.PooledConnectionFactory)

Example 2 with SearchConnectionValidator

use of org.ldaptive.SearchConnectionValidator in project cas by apereo.

the class LdapMonitorConfiguration method pooledLdapConnectionFactoryHealthIndicator.

@Bean
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
@ConditionalOnEnabledHealthIndicator("pooledLdapConnectionFactoryHealthIndicator")
public CompositeHealthContributor pooledLdapConnectionFactoryHealthIndicator(final CasConfigurationProperties casProperties, @Qualifier("pooledLdapConnectionFactoryHealthIndicatorListFactoryBean") final ListFactoryBean factoryBean) throws Exception {
    val ldaps = casProperties.getMonitor().getLdap();
    val connectionFactoryList = Objects.requireNonNull(factoryBean.getObject());
    val contributors = new LinkedHashMap<>();
    ldaps.stream().filter(LdapMonitorProperties::isEnabled).map(Unchecked.function(ldap -> {
        val executor = Beans.newThreadPoolExecutorFactoryBean(ldap.getPool());
        val connectionFactory = LdapUtils.newLdaptivePooledConnectionFactory(ldap);
        connectionFactoryList.add(connectionFactory);
        val healthIndicator = new PooledLdapConnectionFactoryHealthIndicator(Beans.newDuration(ldap.getMaxWait()).toMillis(), connectionFactory, executor.getObject(), new SearchConnectionValidator());
        val name = StringUtils.defaultIfBlank(ldap.getName(), UUID.randomUUID().toString());
        return Pair.of(name, healthIndicator);
    })).forEach(it -> contributors.put(it.getKey(), it.getValue()));
    return CompositeHealthContributor.fromMap((Map) contributors);
}
Also used : lombok.val(lombok.val) SearchConnectionValidator(org.ldaptive.SearchConnectionValidator) LdapMonitorProperties(org.apereo.cas.configuration.model.core.monitor.LdapMonitorProperties) PooledLdapConnectionFactoryHealthIndicator(org.apereo.cas.monitor.PooledLdapConnectionFactoryHealthIndicator) LinkedHashMap(java.util.LinkedHashMap) RefreshScope(org.springframework.cloud.context.config.annotation.RefreshScope) ConditionalOnEnabledHealthIndicator(org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator) ListFactoryBean(org.springframework.beans.factory.config.ListFactoryBean) Bean(org.springframework.context.annotation.Bean)

Aggregations

LinkedHashMap (java.util.LinkedHashMap)2 lombok.val (lombok.val)2 Multimap (com.google.common.collect.Multimap)1 URI (java.net.URI)1 URL (java.net.URL)1 StandardCharsets (java.nio.charset.StandardCharsets)1 Period (java.time.Period)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Map (java.util.Map)1 Objects (java.util.Objects)1 Set (java.util.Set)1 Collectors (java.util.stream.Collectors)1 IntStream (java.util.stream.IntStream)1 AccountNotFoundException (javax.security.auth.login.AccountNotFoundException)1 RequiredArgsConstructor (lombok.RequiredArgsConstructor)1 SneakyThrows (lombok.SneakyThrows)1 UtilityClass (lombok.experimental.UtilityClass)1