Search in sources :

Example 6 with StringUtils

use of org.apache.commons.lang3.StringUtils in project cas by apereo.

the class AbstractX509PrincipalResolver method getAlternatePrincipal.

/**
 * Get alternate principal if alternate attribute configured.
 *
 * @param certificate X509 Certificate of user
 * @return principal using alternate attribute or null if none configured
 */
protected String getAlternatePrincipal(final X509Certificate certificate) {
    if (StringUtils.isBlank(alternatePrincipalAttribute)) {
        return null;
    }
    val attributes = extractPersonAttributes(certificate);
    val attribute = attributes.get(alternatePrincipalAttribute);
    if (attribute == null) {
        LOGGER.debug("Attempt to get alternate principal with attribute [{}] was unsuccessful.", alternatePrincipalAttribute);
        return null;
    }
    val optionalAttribute = CollectionUtils.firstElement(attribute);
    return optionalAttribute.map(Object::toString).filter(StringUtils::isNotEmpty).map(alternatePrincipal -> {
        LOGGER.debug("Using alternate principal attribute [{}]", alternatePrincipal);
        return alternatePrincipal;
    }).orElseGet(() -> {
        LOGGER.trace("Returning null principal id...");
        return null;
    });
}
Also used : lombok.val(lombok.val) X509Certificate(java.security.cert.X509Certificate) PersonDirectoryPrincipalResolver(org.apereo.cas.authentication.principal.resolvers.PersonDirectoryPrincipalResolver) Setter(lombok.Setter) lombok.val(lombok.val) StringUtils(org.apache.commons.lang3.StringUtils) LinkedHashMap(java.util.LinkedHashMap) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) Map(java.util.Map) CollectionUtils(org.apereo.cas.util.CollectionUtils) ToString(lombok.ToString) Optional(java.util.Optional) Principal(org.apereo.cas.authentication.principal.Principal) PrincipalResolutionContext(org.apereo.cas.authentication.principal.resolvers.PrincipalResolutionContext) Credential(org.apereo.cas.authentication.Credential) StringUtils(org.apache.commons.lang3.StringUtils)

Example 7 with StringUtils

use of org.apache.commons.lang3.StringUtils in project cas by apereo.

the class CoreAuthenticationUtils method buildPrincipalResolutionContext.

/**
 * New PrincipalResolutionContext.
 *
 * @param principalFactory    the principal factory
 * @param attributeRepository the attribute repository
 * @param attributeMerger     the attribute merger
 * @param personDirectory     the person directory properties
 * @return the resolver
 */
public static PrincipalResolutionContext buildPrincipalResolutionContext(final PrincipalFactory principalFactory, final IPersonAttributeDao attributeRepository, final IAttributeMerger attributeMerger, final PersonDirectoryPrincipalResolverProperties... personDirectory) {
    val transformers = Arrays.stream(personDirectory).map(p -> PrincipalNameTransformerUtils.newPrincipalNameTransformer(p.getPrincipalTransformation())).collect(Collectors.toList());
    val transformer = new ChainingPrincipalNameTransformer(transformers);
    return PrincipalResolutionContext.builder().attributeRepository(attributeRepository).attributeMerger(attributeMerger).principalFactory(principalFactory).returnNullIfNoAttributes(Arrays.stream(personDirectory).filter(p -> p.getReturnNull() != TriStateBoolean.UNDEFINED).map(p -> p.getReturnNull().toBoolean()).findFirst().orElse(Boolean.FALSE)).principalAttributeNames(Arrays.stream(personDirectory).map(PersonDirectoryPrincipalResolverProperties::getPrincipalAttribute).filter(StringUtils::isNotBlank).findFirst().orElse(StringUtils.EMPTY)).principalNameTransformer(transformer).useCurrentPrincipalId(Arrays.stream(personDirectory).filter(p -> p.getUseExistingPrincipalId() != TriStateBoolean.UNDEFINED).map(p -> p.getUseExistingPrincipalId().toBoolean()).findFirst().orElse(Boolean.FALSE)).resolveAttributes(Arrays.stream(personDirectory).filter(p -> p.getAttributeResolutionEnabled() != TriStateBoolean.UNDEFINED).map(p -> p.getAttributeResolutionEnabled().toBoolean()).findFirst().orElse(Boolean.TRUE)).activeAttributeRepositoryIdentifiers(Arrays.stream(personDirectory).filter(p -> StringUtils.isNotBlank(p.getActiveAttributeRepositoryIds())).map(p -> org.springframework.util.StringUtils.commaDelimitedListToSet(p.getActiveAttributeRepositoryIds())).filter(p -> !p.isEmpty()).findFirst().orElse(Collections.EMPTY_SET)).build();
}
Also used : lombok.val(lombok.val) ArrayListMultimap(com.google.common.collect.ArrayListMultimap) Arrays(java.util.Arrays) ReplacingAttributeAdder(org.apereo.services.persondir.support.merger.ReplacingAttributeAdder) GroovyPasswordPolicyHandlingStrategy(org.apereo.cas.authentication.support.password.GroovyPasswordPolicyHandlingStrategy) Assertion(org.apereo.cas.validation.Assertion) GroovyIPAddressIntelligenceService(org.apereo.cas.authentication.adaptive.intel.GroovyIPAddressIntelligenceService) Beans(org.apereo.cas.configuration.support.Beans) StringUtils(org.apache.commons.lang3.StringUtils) IPersonAttributeDao(org.apereo.services.persondir.IPersonAttributeDao) ClassUtils(org.apache.commons.lang3.ClassUtils) PrincipalFactory(org.apereo.cas.authentication.principal.PrincipalFactory) Pair(org.apache.commons.lang3.tuple.Pair) Map(java.util.Map) Splitter(com.google.common.base.Splitter) DefaultIPAddressIntelligenceService(org.apereo.cas.authentication.adaptive.intel.DefaultIPAddressIntelligenceService) Unchecked(org.jooq.lambda.Unchecked) Predicate(java.util.function.Predicate) Collection(java.util.Collection) PrincipalResolver(org.apereo.cas.authentication.principal.PrincipalResolver) IAttributeMerger(org.apereo.services.persondir.support.merger.IAttributeMerger) Set(java.util.Set) MultivaluedAttributeMerger(org.apereo.services.persondir.support.merger.MultivaluedAttributeMerger) AuthenticationPolicyProperties(org.apereo.cas.configuration.model.core.authentication.AuthenticationPolicyProperties) Collectors(java.util.stream.Collectors) PasswordPolicyProperties(org.apereo.cas.configuration.model.core.authentication.PasswordPolicyProperties) IPersonAttributeDaoFilter(org.apereo.services.persondir.IPersonAttributeDaoFilter) StandardCharsets(java.nio.charset.StandardCharsets) RejectResultCodePasswordPolicyHandlingStrategy(org.apereo.cas.authentication.support.password.RejectResultCodePasswordPolicyHandlingStrategy) IOUtils(org.apache.commons.io.IOUtils) AllCredentialsValidatedAuthenticationPolicy(org.apereo.cas.authentication.policy.AllCredentialsValidatedAuthenticationPolicy) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) IPAddressIntelligenceService(org.apereo.cas.authentication.adaptive.intel.IPAddressIntelligenceService) Optional(java.util.Optional) Principal(org.apereo.cas.authentication.principal.Principal) PrincipalResolutionContext(org.apereo.cas.authentication.principal.resolvers.PrincipalResolutionContext) Pattern(java.util.regex.Pattern) GroovyClassLoader(groovy.lang.GroovyClassLoader) AtLeastOneCredentialValidatedAuthenticationPolicy(org.apereo.cas.authentication.policy.AtLeastOneCredentialValidatedAuthenticationPolicy) RequiredAuthenticationHandlerAuthenticationPolicy(org.apereo.cas.authentication.policy.RequiredAuthenticationHandlerAuthenticationPolicy) AllAuthenticationHandlersSucceededAuthenticationPolicy(org.apereo.cas.authentication.policy.AllAuthenticationHandlersSucceededAuthenticationPolicy) ArrayUtils(org.apache.commons.lang3.ArrayUtils) HashMap(java.util.HashMap) RestfulIPAddressIntelligenceService(org.apereo.cas.authentication.adaptive.intel.RestfulIPAddressIntelligenceService) Multimap(com.google.common.collect.Multimap) PersonDirectoryPrincipalResolverProperties(org.apereo.cas.configuration.model.core.authentication.PersonDirectoryPrincipalResolverProperties) NoncollidingAttributeAdder(org.apereo.services.persondir.support.merger.NoncollidingAttributeAdder) ArrayList(java.util.ArrayList) UtilityClass(lombok.experimental.UtilityClass) LinkedHashMap(java.util.LinkedHashMap) NotPreventedAuthenticationPolicy(org.apereo.cas.authentication.policy.NotPreventedAuthenticationPolicy) DefaultResourceLoader(org.springframework.core.io.DefaultResourceLoader) CollectionUtils(org.apereo.cas.util.CollectionUtils) ChainingPrincipalNameTransformer(org.apereo.cas.util.transforms.ChainingPrincipalNameTransformer) PersonDirectoryPrincipalResolver(org.apereo.cas.authentication.principal.resolvers.PersonDirectoryPrincipalResolver) BaseAdditiveAttributeMerger(org.apereo.services.persondir.support.merger.BaseAdditiveAttributeMerger) lombok.val(lombok.val) GroovyScriptAuthenticationPolicy(org.apereo.cas.authentication.policy.GroovyScriptAuthenticationPolicy) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) ApplicationContext(org.springframework.context.ApplicationContext) AdaptiveAuthenticationProperties(org.apereo.cas.configuration.model.core.authentication.AdaptiveAuthenticationProperties) TriStateBoolean(org.apereo.cas.util.model.TriStateBoolean) PrincipalNameTransformerUtils(org.apereo.cas.authentication.principal.PrincipalNameTransformerUtils) DefaultPasswordPolicyHandlingStrategy(org.apereo.cas.authentication.support.password.DefaultPasswordPolicyHandlingStrategy) PrincipalAttributesCoreProperties(org.apereo.cas.configuration.model.core.authentication.PrincipalAttributesCoreProperties) RestfulAuthenticationPolicy(org.apereo.cas.authentication.policy.RestfulAuthenticationPolicy) Collections(java.util.Collections) StringUtils(org.apache.commons.lang3.StringUtils) ChainingPrincipalNameTransformer(org.apereo.cas.util.transforms.ChainingPrincipalNameTransformer)

Example 8 with StringUtils

use of org.apache.commons.lang3.StringUtils in project cas by apereo.

the class ServiceValidationViewFactory method getValidationResponseType.

/**
 * Gets validation response type.
 *
 * @param request the request
 * @param service the service
 * @return the validation response type
 */
private static ValidationResponseType getValidationResponseType(final HttpServletRequest request, final WebApplicationService service) {
    val format = request.getParameter(CasProtocolConstants.PARAMETER_FORMAT);
    final Function<String, ValidationResponseType> func = FunctionUtils.doIf(StringUtils::isNotBlank, t -> ValidationResponseType.valueOf(t.toUpperCase()), f -> service != null ? service.getFormat() : ValidationResponseType.XML);
    return func.apply(format);
}
Also used : lombok.val(lombok.val) ValidationResponseType(org.apereo.cas.validation.ValidationResponseType) StringUtils(org.apache.commons.lang3.StringUtils)

Example 9 with StringUtils

use of org.apache.commons.lang3.StringUtils in project cas by apereo.

the class MongoDbConnectionFactory method buildMongoDbClient.

/**
 * Build mongo db client.
 *
 * @param mongo the mongo
 * @return the mongo client
 */
public MongoClient buildMongoDbClient(final BaseMongoDbProperties mongo) {
    val settingsBuilder = MongoClientSettings.builder();
    if (StringUtils.isNotBlank(mongo.getClientUri())) {
        LOGGER.debug("Using MongoDb client URI [{}] to connect to MongoDb instance", mongo.getClientUri());
        settingsBuilder.applyConnectionString(new ConnectionString(mongo.getClientUri()));
    } else {
        val serverAddresses = mongo.getHost().split(",");
        if (serverAddresses.length == 0) {
            throw new BeanCreationException("Unable to build a MongoDb client without any hosts/servers defined");
        }
        val servers = new ArrayList<ServerAddress>(0);
        if (serverAddresses.length > 1) {
            LOGGER.debug("Multiple MongoDb server addresses are defined. Ignoring port [{}], " + "assuming ports are defined as part of the address", mongo.getPort());
            Arrays.stream(serverAddresses).filter(StringUtils::isNotBlank).map(ServerAddress::new).forEach(servers::add);
        } else {
            val port = mongo.getPort() > 0 ? mongo.getPort() : DEFAULT_PORT;
            LOGGER.debug("Found single MongoDb server address [{}] using port [{}]", mongo.getHost(), port);
            val addr = new ServerAddress(mongo.getHost(), port);
            servers.add(addr);
        }
        settingsBuilder.applyToClusterSettings(builder -> builder.hosts(servers));
        val credential = buildMongoCredential(mongo);
        settingsBuilder.credential(credential).writeConcern(WriteConcern.valueOf(mongo.getWriteConcern())).codecRegistry(CodecRegistries.fromRegistries(CodecRegistries.fromProviders(new BaseConverters.ZonedDateTimeCodecProvider()), MongoClientSettings.getDefaultCodecRegistry())).readConcern(new ReadConcern(ReadConcernLevel.valueOf(mongo.getReadConcern()))).applyToConnectionPoolSettings(builder -> {
            val poolConfig = mongo.getPool();
            val pool = ConnectionPoolSettings.builder().maxConnectionLifeTime(Beans.newDuration(poolConfig.getLifeTime()).toMillis(), TimeUnit.MILLISECONDS).maxConnectionIdleTime(Beans.newDuration(poolConfig.getIdleTime()).toMillis(), TimeUnit.MILLISECONDS).maxSize(poolConfig.getMaxSize()).minSize(poolConfig.getMinSize()).maxWaitTime(Beans.newDuration(poolConfig.getMaxWaitTime()).toMillis(), TimeUnit.MILLISECONDS).build();
            builder.applySettings(pool);
        }).applyToSocketSettings(builder -> {
            val socket = SocketSettings.builder().connectTimeout((int) Beans.newDuration(mongo.getTimeout()).toMillis(), TimeUnit.MILLISECONDS).readTimeout((int) Beans.newDuration(mongo.getTimeout()).toMillis(), TimeUnit.MILLISECONDS).build();
            builder.applySettings(socket);
        }).applyToSslSettings(builder -> {
            val ssl = SslSettings.builder().enabled(mongo.isSslEnabled()).context(this.sslContext).build();
            builder.applySettings(ssl);
        }).applyToServerSettings(builder -> {
            val server = ServerSettings.builder().heartbeatFrequency((int) Beans.newDuration(mongo.getTimeout()).toMillis(), TimeUnit.MILLISECONDS).build();
            builder.applySettings(server);
        }).retryWrites(mongo.isRetryWrites());
    }
    return MongoClients.create(settingsBuilder.build());
}
Also used : lombok.val(lombok.val) SSLContext(javax.net.ssl.SSLContext) Arrays(java.util.Arrays) SneakyThrows(lombok.SneakyThrows) Beans(org.apereo.cas.configuration.support.Beans) StringUtils(org.apache.commons.lang3.StringUtils) Document(org.springframework.data.mongodb.core.mapping.Document) LoggingUtils(org.apereo.cas.util.LoggingUtils) SocketSettings(com.mongodb.connection.SocketSettings) SSLContexts(org.apache.http.ssl.SSLContexts) ReadConcern(com.mongodb.ReadConcern) AnnotationTypeFilter(org.springframework.core.type.filter.AnnotationTypeFilter) ClassUtils(org.springframework.util.ClassUtils) PropertyNameFieldNamingStrategy(org.springframework.data.mapping.model.PropertyNameFieldNamingStrategy) MongoClients(com.mongodb.client.MongoClients) Collection(java.util.Collection) Set(java.util.Set) CodecRegistries(org.bson.codecs.configuration.CodecRegistries) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) Stream(java.util.stream.Stream) JodaTimeConverters(org.springframework.data.convert.JodaTimeConverters) MongoClientSettings(com.mongodb.MongoClientSettings) IndexDefinition(org.springframework.data.mongodb.core.index.IndexDefinition) ConnectionPoolSettings(com.mongodb.connection.ConnectionPoolSettings) MongoMappingContext(org.springframework.data.mongodb.core.mapping.MongoMappingContext) MongoCredential(com.mongodb.MongoCredential) MongoClient(com.mongodb.client.MongoClient) MongoCollection(com.mongodb.client.MongoCollection) MongoCustomConversions(org.springframework.data.mongodb.core.convert.MongoCustomConversions) FieldNamingStrategy(org.springframework.data.mapping.model.FieldNamingStrategy) MongoDatabaseFactory(org.springframework.data.mongodb.MongoDatabaseFactory) ServerSettings(com.mongodb.connection.ServerSettings) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) BeanCreationException(org.springframework.beans.factory.BeanCreationException) CollectionUtils(org.apereo.cas.util.CollectionUtils) Jsr310Converters(org.springframework.data.convert.Jsr310Converters) ServerAddress(com.mongodb.ServerAddress) SslSettings(com.mongodb.connection.SslSettings) Converter(org.springframework.core.convert.converter.Converter) Persistent(org.springframework.data.annotation.Persistent) ClassPathScanningCandidateComponentProvider(org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider) lombok.val(lombok.val) TimeUnit(java.util.concurrent.TimeUnit) MappingMongoConverter(org.springframework.data.mongodb.core.convert.MappingMongoConverter) ConnectionString(com.mongodb.ConnectionString) ReadConcernLevel(com.mongodb.ReadConcernLevel) BaseMongoDbProperties(org.apereo.cas.configuration.model.support.mongo.BaseMongoDbProperties) MongoOperations(org.springframework.data.mongodb.core.MongoOperations) DefaultDbRefResolver(org.springframework.data.mongodb.core.convert.DefaultDbRefResolver) WriteConcern(com.mongodb.WriteConcern) SimpleMongoClientDatabaseFactory(org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory) BeanCreationException(org.springframework.beans.factory.BeanCreationException) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) ServerAddress(com.mongodb.ServerAddress) ConnectionString(com.mongodb.ConnectionString) ReadConcern(com.mongodb.ReadConcern)

Example 10 with StringUtils

use of org.apache.commons.lang3.StringUtils in project cas by apereo.

the class OidcClientRegistrationUtils method getClientRegistrationResponse.

/**
 * Gets client registration response.
 *
 * @param registeredService the registered service
 * @param serverPrefix      the server prefix
 * @return the client registration response
 */
@SneakyThrows
public static OidcClientRegistrationResponse getClientRegistrationResponse(final OidcRegisteredService registeredService, final String serverPrefix) {
    val clientResponse = new OidcClientRegistrationResponse();
    clientResponse.setApplicationType(registeredService.getApplicationType());
    clientResponse.setClientId(registeredService.getClientId());
    clientResponse.setClientSecret(registeredService.getClientSecret());
    clientResponse.setSubjectType(registeredService.getSubjectType());
    clientResponse.setTokenEndpointAuthMethod(registeredService.getTokenEndpointAuthenticationMethod());
    clientResponse.setClientName(registeredService.getName());
    clientResponse.setRedirectUris(CollectionUtils.wrap(registeredService.getServiceId()));
    clientResponse.setUserInfoSignedReponseAlg(registeredService.getUserInfoSigningAlg());
    clientResponse.setUserInfoEncryptedReponseAlg(registeredService.getUserInfoEncryptedResponseAlg());
    clientResponse.setUserInfoEncryptedReponseEncoding(registeredService.getUserInfoEncryptedResponseEncoding());
    clientResponse.setContacts(registeredService.getContacts().stream().map(RegisteredServiceContact::getName).filter(StringUtils::isNotBlank).collect(Collectors.toList()));
    clientResponse.setGrantTypes(Arrays.stream(OAuth20GrantTypes.values()).map(type -> type.getType().toLowerCase()).collect(Collectors.toList()));
    clientResponse.setResponseTypes(Arrays.stream(OAuth20ResponseTypes.values()).map(type -> type.getType().toLowerCase()).collect(Collectors.toList()));
    val validator = new SimpleUrlValidatorFactoryBean(false).getObject();
    val keystore = SpringExpressionLanguageValueResolver.getInstance().resolve(registeredService.getJwks());
    if (Objects.requireNonNull(validator).isValid(keystore)) {
        clientResponse.setJwksUri(keystore);
    } else if (ResourceUtils.doesResourceExist(keystore)) {
        val res = ResourceUtils.getResourceFrom(keystore);
        val json = IOUtils.toString(res.getInputStream(), StandardCharsets.UTF_8);
        clientResponse.setJwks(new JsonWebKeySet(json).toJson());
    } else if (StringUtils.isNotBlank(keystore)) {
        val jwks = new JsonWebKeySet(keystore);
        clientResponse.setJwks(jwks.toJson());
    }
    clientResponse.setLogo(registeredService.getLogo());
    clientResponse.setPolicyUri(registeredService.getInformationUrl());
    clientResponse.setTermsOfUseUri(registeredService.getPrivacyUrl());
    clientResponse.setRedirectUris(CollectionUtils.wrapList(registeredService.getServiceId()));
    val clientConfigUri = getClientConfigurationUri(registeredService, serverPrefix);
    clientResponse.setRegistrationClientUri(clientConfigUri);
    return clientResponse;
}
Also used : lombok.val(lombok.val) SimpleUrlValidatorFactoryBean(org.apereo.cas.web.SimpleUrlValidatorFactoryBean) StringUtils(org.apache.commons.lang3.StringUtils) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet) OidcClientRegistrationResponse(org.apereo.cas.oidc.dynareg.OidcClientRegistrationResponse) SneakyThrows(lombok.SneakyThrows)

Aggregations

StringUtils (org.apache.commons.lang3.StringUtils)29 HashMap (java.util.HashMap)10 List (java.util.List)10 Optional (java.util.Optional)10 Map (java.util.Map)9 Collectors (java.util.stream.Collectors)8 Set (java.util.Set)7 lombok.val (lombok.val)7 ArrayList (java.util.ArrayList)6 Arrays (java.util.Arrays)5 Stream (java.util.stream.Stream)5 ColumnSpec (com.thinkbiganalytics.util.ColumnSpec)3 Collection (java.util.Collection)3 HashSet (java.util.HashSet)3 Slf4j (lombok.extern.slf4j.Slf4j)3 FlowFile (org.apache.nifi.flowfile.FlowFile)3 CollectionUtils (org.apereo.cas.util.CollectionUtils)3 AlertException (com.synopsys.integration.alert.api.common.model.exception.AlertException)2 ThriftService (com.thinkbiganalytics.nifi.v2.thrift.ThriftService)2 IOException (java.io.IOException)2