Search in sources :

Example 6 with StringUtils.isNotBlank

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

the class SamlSPUtils method newSamlServiceProviderService.

/**
     * New saml service provider registration.
     *
     * @param sp       the properties
     * @param resolver the resolver
     * @return the saml registered service
     */
public static SamlRegisteredService newSamlServiceProviderService(final AbstractSamlSPProperties sp, final SamlRegisteredServiceCachingMetadataResolver resolver) {
    if (StringUtils.isBlank(sp.getMetadata())) {
        LOGGER.debug("Skipped registration of [{}] since no metadata location is found", sp.getName());
        return null;
    }
    try {
        final SamlRegisteredService service = new SamlRegisteredService();
        service.setName(sp.getName());
        service.setDescription(sp.getDescription());
        service.setEvaluationOrder(Integer.MIN_VALUE);
        service.setMetadataLocation(sp.getMetadata());
        final List<String> attributesToRelease = new ArrayList<>(sp.getAttributes());
        if (StringUtils.isNotBlank(sp.getNameIdAttribute())) {
            attributesToRelease.add(sp.getNameIdAttribute());
            service.setUsernameAttributeProvider(new PrincipalAttributeRegisteredServiceUsernameProvider(sp.getNameIdAttribute()));
        }
        if (StringUtils.isNotBlank(sp.getNameIdFormat())) {
            service.setRequiredNameIdFormat(sp.getNameIdFormat());
        }
        final Map<String, String> attributes = Beans.transformPrincipalAttributesListIntoMap(attributesToRelease);
        service.setAttributeReleasePolicy(new ReturnMappedAttributeReleasePolicy(attributes));
        service.setMetadataCriteriaRoles(SPSSODescriptor.DEFAULT_ELEMENT_NAME.getLocalPart());
        service.setMetadataCriteriaRemoveEmptyEntitiesDescriptors(true);
        service.setMetadataCriteriaRemoveRolelessEntityDescriptors(true);
        if (StringUtils.isNotBlank(sp.getSignatureLocation())) {
            service.setMetadataSignatureLocation(sp.getSignatureLocation());
        }
        final List<String> entityIDList = sp.getEntityIds();
        if (entityIDList.isEmpty()) {
            final ChainingMetadataResolver chainingResolver = resolver.resolve(service);
            if (chainingResolver.getResolvers().isEmpty()) {
                LOGGER.warn("Skipped registration of [{}] since no metadata resolver could be constructed", sp.getName());
                return null;
            }
            chainingResolver.getResolvers().forEach(r -> {
                if (r instanceof AbstractBatchMetadataResolver) {
                    final Iterator<EntityDescriptor> it = ((AbstractBatchMetadataResolver) r).iterator();
                    final Optional<EntityDescriptor> descriptor = StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, Spliterator.ORDERED), false).filter(e -> e.getSPSSODescriptor(SAMLConstants.SAML20P_NS) != null).findFirst();
                    if (descriptor.isPresent()) {
                        entityIDList.add(descriptor.get().getEntityID());
                    } else {
                        LOGGER.warn("Skipped registration of [{}] since no entity id could be found", sp.getName());
                    }
                }
            });
        }
        if (entityIDList.isEmpty()) {
            LOGGER.warn("Skipped registration of [{}] since no metadata entity ids could be found", sp.getName());
            return null;
        }
        final String entityIds = org.springframework.util.StringUtils.collectionToDelimitedString(entityIDList, "|");
        service.setMetadataCriteriaDirection(PredicateFilter.Direction.INCLUDE.name());
        service.setMetadataCriteriaPattern(entityIds);
        LOGGER.debug("Registering saml service [{}] by entity id [{}]", sp.getName(), entityIds);
        service.setServiceId(entityIds);
        return service;
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
Also used : AbstractBatchMetadataResolver(org.opensaml.saml.metadata.resolver.impl.AbstractBatchMetadataResolver) PrincipalAttributeRegisteredServiceUsernameProvider(org.apereo.cas.services.PrincipalAttributeRegisteredServiceUsernameProvider) Spliterators(java.util.Spliterators) SamlRegisteredServiceCachingMetadataResolver(org.apereo.cas.support.saml.services.idp.metadata.cache.SamlRegisteredServiceCachingMetadataResolver) LoggerFactory(org.slf4j.LoggerFactory) Beans(org.apereo.cas.configuration.support.Beans) StringUtils(org.apache.commons.lang3.StringUtils) AbstractBatchMetadataResolver(org.opensaml.saml.metadata.resolver.impl.AbstractBatchMetadataResolver) ArrayList(java.util.ArrayList) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) Map(java.util.Map) StreamSupport(java.util.stream.StreamSupport) SAMLConstants(org.opensaml.saml.common.xml.SAMLConstants) ServicesManager(org.apereo.cas.services.ServicesManager) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) Throwables(com.google.common.base.Throwables) RegisteredService(org.apereo.cas.services.RegisteredService) SPSSODescriptor(org.opensaml.saml.saml2.metadata.SPSSODescriptor) List(java.util.List) AbstractSamlSPProperties(org.apereo.cas.configuration.model.support.saml.sps.AbstractSamlSPProperties) ReturnMappedAttributeReleasePolicy(org.apereo.cas.services.ReturnMappedAttributeReleasePolicy) ChainingMetadataResolver(org.opensaml.saml.metadata.resolver.ChainingMetadataResolver) Optional(java.util.Optional) EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) PredicateFilter(org.opensaml.saml.metadata.resolver.filter.impl.PredicateFilter) Spliterator(java.util.Spliterator) ArrayList(java.util.ArrayList) EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) ChainingMetadataResolver(org.opensaml.saml.metadata.resolver.ChainingMetadataResolver) PrincipalAttributeRegisteredServiceUsernameProvider(org.apereo.cas.services.PrincipalAttributeRegisteredServiceUsernameProvider) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) ReturnMappedAttributeReleasePolicy(org.apereo.cas.services.ReturnMappedAttributeReleasePolicy)

Example 7 with StringUtils.isNotBlank

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

the class Pac4jAuthenticationEventExecutionPlanConfiguration method configureSamlClient.

private void configureSamlClient(final Collection<BaseClient> properties) {
    final AtomicInteger index = new AtomicInteger();
    casProperties.getAuthn().getPac4j().getSaml().stream().filter(saml -> StringUtils.isNotBlank(saml.getKeystorePath()) && StringUtils.isNotBlank(saml.getIdentityProviderMetadataPath())).forEach(saml -> {
        final SAML2ClientConfiguration cfg = new SAML2ClientConfiguration(saml.getKeystorePath(), saml.getKeystorePassword(), saml.getPrivateKeyPassword(), saml.getIdentityProviderMetadataPath());
        cfg.setMaximumAuthenticationLifetime(saml.getMaximumAuthenticationLifetime());
        cfg.setServiceProviderEntityId(saml.getServiceProviderEntityId());
        cfg.setServiceProviderMetadataPath(saml.getServiceProviderMetadataPath());
        cfg.setDestinationBindingType(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
        final SAML2Client client = new SAML2Client(cfg);
        client.setName(client.getClass().getSimpleName() + index.incrementAndGet());
        properties.add(client);
    });
}
Also used : CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) CasConfiguration(org.pac4j.cas.config.CasConfiguration) CasClient(org.pac4j.cas.client.CasClient) Google2Client(org.pac4j.oauth.client.Google2Client) OidcConfiguration(org.pac4j.oidc.config.OidcConfiguration) SAML2Client(org.pac4j.saml.client.SAML2Client) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) StringUtils(org.apache.commons.lang3.StringUtils) AuthenticationEventExecutionPlan(org.apereo.cas.authentication.AuthenticationEventExecutionPlan) YahooClient(org.pac4j.oauth.client.YahooClient) RefreshScope(org.springframework.cloud.context.config.annotation.RefreshScope) AuthenticationHandler(org.apereo.cas.authentication.AuthenticationHandler) PrincipalFactory(org.apereo.cas.authentication.principal.PrincipalFactory) Clients(org.pac4j.core.client.Clients) LinkedIn2Client(org.pac4j.oauth.client.LinkedIn2Client) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ClientAuthenticationHandler(org.apereo.cas.support.pac4j.authentication.handler.support.ClientAuthenticationHandler) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) ClientAuthenticationMetaDataPopulator(org.apereo.cas.support.pac4j.authentication.ClientAuthenticationMetaDataPopulator) Verb(com.github.scribejava.core.model.Verb) Collection(java.util.Collection) PrincipalResolver(org.apereo.cas.authentication.principal.PrincipalResolver) Set(java.util.Set) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) SAML2ClientLogoutAction(org.apereo.cas.support.pac4j.web.flow.SAML2ClientLogoutAction) Action(org.springframework.webflow.execution.Action) AuthenticationEventExecutionPlanConfigurer(org.apereo.cas.config.support.authentication.AuthenticationEventExecutionPlanConfigurer) Configuration(org.springframework.context.annotation.Configuration) BaseClient(org.pac4j.core.client.BaseClient) FoursquareClient(org.pac4j.oauth.client.FoursquareClient) GitHubClient(org.pac4j.oauth.client.GitHubClient) SAML2ClientConfiguration(org.pac4j.saml.client.SAML2ClientConfiguration) AuthenticationMetaDataPopulator(org.apereo.cas.authentication.AuthenticationMetaDataPopulator) WindowsLiveClient(org.pac4j.oauth.client.WindowsLiveClient) AzureAdClient(org.pac4j.oidc.client.AzureAdClient) BitbucketClient(org.pac4j.oauth.client.BitbucketClient) WordPressClient(org.pac4j.oauth.client.WordPressClient) ArrayList(java.util.ArrayList) OidcClient(org.pac4j.oidc.client.OidcClient) Qualifier(org.springframework.beans.factory.annotation.Qualifier) PayPalClient(org.pac4j.oauth.client.PayPalClient) SAMLConstants(org.opensaml.saml.common.xml.SAMLConstants) LinkedHashSet(java.util.LinkedHashSet) ServicesManager(org.apereo.cas.services.ServicesManager) GoogleOidcClient(org.pac4j.oidc.client.GoogleOidcClient) Logger(org.slf4j.Logger) FacebookClient(org.pac4j.oauth.client.FacebookClient) GenericOAuth20Client(org.pac4j.oauth.client.GenericOAuth20Client) Pac4jProperties(org.apereo.cas.configuration.model.support.pac4j.Pac4jProperties) TwitterClient(org.pac4j.oauth.client.TwitterClient) Bean(org.springframework.context.annotation.Bean) DefaultPrincipalFactory(org.apereo.cas.authentication.principal.DefaultPrincipalFactory) DropBoxClient(org.pac4j.oauth.client.DropBoxClient) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SAML2Client(org.pac4j.saml.client.SAML2Client) SAML2ClientConfiguration(org.pac4j.saml.client.SAML2ClientConfiguration)

Example 8 with StringUtils.isNotBlank

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

the class ClickatellSmsSender method send.

@Override
public boolean send(final String from, final String to, final String message) {
    try {
        final MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Authorization", this.token);
        headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
        final Map<String, Object> map = new HashMap<>();
        map.put("content", message);
        map.put("to", Arrays.asList(to));
        map.put("from", from);
        final StringWriter stringify = new StringWriter();
        mapper.writeValue(stringify, map);
        final HttpEntity<String> request = new HttpEntity<>(stringify.toString(), headers);
        final ResponseEntity<Map> response = restTemplate.postForEntity(new URI(this.serverUrl), request, Map.class);
        if (response.hasBody()) {
            final List<Map> messages = (List<Map>) response.getBody().get("messages");
            final String error = (String) response.getBody().get("error");
            if (StringUtils.isNotBlank(error)) {
                LOGGER.error(error);
                return false;
            }
            final List<String> errors = messages.stream().filter(m -> m.containsKey("accepted") && !Boolean.valueOf(m.get("accepted").toString()) && m.containsKey("error")).map(m -> (String) m.get("error")).collect(Collectors.toList());
            if (errors.isEmpty()) {
                return true;
            }
            errors.forEach(LOGGER::error);
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return false;
}
Also used : Arrays(java.util.Arrays) Logger(org.slf4j.Logger) MediaType(org.springframework.http.MediaType) StringWriter(java.io.StringWriter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) LoggerFactory(org.slf4j.LoggerFactory) MultiValueMap(org.springframework.util.MultiValueMap) HashMap(java.util.HashMap) StringUtils(org.apache.commons.lang3.StringUtils) Collectors(java.util.stream.Collectors) HttpEntity(org.springframework.http.HttpEntity) List(java.util.List) MappingJackson2HttpMessageConverter(org.springframework.http.converter.json.MappingJackson2HttpMessageConverter) Map(java.util.Map) ResponseEntity(org.springframework.http.ResponseEntity) URI(java.net.URI) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) RestTemplate(org.springframework.web.client.RestTemplate) SmsSender(org.apereo.cas.util.io.SmsSender) HttpEntity(org.springframework.http.HttpEntity) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) HashMap(java.util.HashMap) URI(java.net.URI) StringWriter(java.io.StringWriter) List(java.util.List) MultiValueMap(org.springframework.util.MultiValueMap) HashMap(java.util.HashMap) Map(java.util.Map) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap)

Example 9 with StringUtils.isNotBlank

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

the class CasCoreAuthenticationHandlersConfiguration method getParsedUsers.

private Map<String, String> getParsedUsers() {
    final Pattern pattern = Pattern.compile("::");
    final String usersProperty = casProperties.getAuthn().getAccept().getUsers();
    if (StringUtils.isNotBlank(usersProperty) && usersProperty.contains(pattern.pattern())) {
        return Stream.of(usersProperty.split(",")).map(pattern::split).collect(Collectors.toMap(userAndPassword -> userAndPassword[0], userAndPassword -> userAndPassword[1]));
    }
    return Collections.emptyMap();
}
Also used : CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) AcceptAuthenticationProperties(org.apereo.cas.configuration.model.support.generic.AcceptAuthenticationProperties) HttpClient(org.apereo.cas.util.http.HttpClient) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) Beans(org.apereo.cas.configuration.support.Beans) StringUtils(org.apache.commons.lang3.StringUtils) AuthenticationEventExecutionPlan(org.apereo.cas.authentication.AuthenticationEventExecutionPlan) RefreshScope(org.springframework.cloud.context.config.annotation.RefreshScope) AuthenticationHandler(org.apereo.cas.authentication.AuthenticationHandler) PrincipalFactory(org.apereo.cas.authentication.principal.PrincipalFactory) EnableConfigurationProperties(org.springframework.boot.context.properties.EnableConfigurationProperties) Map(java.util.Map) Qualifier(org.springframework.beans.factory.annotation.Qualifier) ServicesManager(org.apereo.cas.services.ServicesManager) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) PrincipalResolver(org.apereo.cas.authentication.principal.PrincipalResolver) Collectors(java.util.stream.Collectors) HttpBasedServiceCredentialsAuthenticationHandler(org.apereo.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler) AuthenticationEventExecutionPlanConfigurer(org.apereo.cas.config.support.authentication.AuthenticationEventExecutionPlanConfigurer) JaasAuthenticationProperties(org.apereo.cas.configuration.model.support.jaas.JaasAuthenticationProperties) Configuration(org.springframework.context.annotation.Configuration) PasswordPolicyConfiguration(org.apereo.cas.authentication.support.password.PasswordPolicyConfiguration) Stream(java.util.stream.Stream) JaasAuthenticationHandler(org.apereo.cas.authentication.handler.support.JaasAuthenticationHandler) Bean(org.springframework.context.annotation.Bean) Pattern(java.util.regex.Pattern) Collections(java.util.Collections) AcceptUsersAuthenticationHandler(org.apereo.cas.authentication.AcceptUsersAuthenticationHandler) DefaultPrincipalFactory(org.apereo.cas.authentication.principal.DefaultPrincipalFactory) ProxyingPrincipalResolver(org.apereo.cas.authentication.principal.resolvers.ProxyingPrincipalResolver) Pattern(java.util.regex.Pattern)

Example 10 with StringUtils.isNotBlank

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

the class OidcJwksEndpointController method handleRequestInternal.

/**
     * Handle request for jwk set.
     *
     * @param request  the request
     * @param response the response
     * @param model    the model
     * @return the jwk set
     * @throws Exception the exception
     */
@GetMapping(value = '/' + OidcConstants.BASE_OIDC_URL + '/' + OidcConstants.JWKS_URL, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response, final Model model) throws Exception {
    Assert.notNull(this.jwksFile, "JWKS file cannot be undefined or null.");
    try {
        final String jsonJwks = IOUtils.toString(this.jwksFile.getInputStream(), StandardCharsets.UTF_8);
        final JsonWebKeySet jsonWebKeySet = new JsonWebKeySet(jsonJwks);
        getServicesManager().getAllServices().stream().filter(s -> s instanceof OidcRegisteredService && StringUtils.isNotBlank(((OidcRegisteredService) s).getJwks())).forEach(Unchecked.consumer(s -> {
            final OidcRegisteredService service = (OidcRegisteredService) s;
            final Resource resource = this.resourceLoader.getResource(service.getJwks());
            final JsonWebKeySet set = new JsonWebKeySet(IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8));
            set.getJsonWebKeys().forEach(jsonWebKeySet::addJsonWebKey);
        }));
        final String body = jsonWebKeySet.toJson(JsonWebKey.OutputControlLevel.PUBLIC_ONLY);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        return new ResponseEntity<>(body, HttpStatus.OK);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
    }
}
Also used : Assert(com.stormpath.sdk.lang.Assert) CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) LoggerFactory(org.slf4j.LoggerFactory) OAuth20Validator(org.apereo.cas.support.oauth.validator.OAuth20Validator) Autowired(org.springframework.beans.factory.annotation.Autowired) BaseOAuthWrapperController(org.apereo.cas.support.oauth.web.BaseOAuthWrapperController) StringUtils(org.apache.commons.lang3.StringUtils) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) Model(org.springframework.ui.Model) HttpServletRequest(javax.servlet.http.HttpServletRequest) PrincipalFactory(org.apereo.cas.authentication.principal.PrincipalFactory) TicketRegistry(org.apereo.cas.ticket.registry.TicketRegistry) GetMapping(org.springframework.web.bind.annotation.GetMapping) ServiceFactory(org.apereo.cas.authentication.principal.ServiceFactory) ServicesManager(org.apereo.cas.services.ServicesManager) Resource(org.springframework.core.io.Resource) Unchecked(org.jooq.lambda.Unchecked) Logger(org.slf4j.Logger) ResourceLoader(org.springframework.core.io.ResourceLoader) OAuth20ProfileScopeToAttributesFilter(org.apereo.cas.support.oauth.profile.OAuth20ProfileScopeToAttributesFilter) OidcConstants(org.apereo.cas.oidc.OidcConstants) JsonWebKey(org.jose4j.jwk.JsonWebKey) MediaType(org.springframework.http.MediaType) HttpServletResponse(javax.servlet.http.HttpServletResponse) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet) StandardCharsets(java.nio.charset.StandardCharsets) IOUtils(org.apache.commons.io.IOUtils) AccessTokenFactory(org.apereo.cas.ticket.accesstoken.AccessTokenFactory) HttpStatus(org.springframework.http.HttpStatus) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) ResponseEntity(org.springframework.http.ResponseEntity) ResponseEntity(org.springframework.http.ResponseEntity) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) Resource(org.springframework.core.io.Resource) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Aggregations

StringUtils (org.apache.commons.lang3.StringUtils)13 Logger (org.slf4j.Logger)12 LoggerFactory (org.slf4j.LoggerFactory)12 ServicesManager (org.apereo.cas.services.ServicesManager)11 CasConfigurationProperties (org.apereo.cas.configuration.CasConfigurationProperties)9 Map (java.util.Map)8 PrincipalFactory (org.apereo.cas.authentication.principal.PrincipalFactory)7 Autowired (org.springframework.beans.factory.annotation.Autowired)7 ArrayList (java.util.ArrayList)6 Collection (java.util.Collection)6 Set (java.util.Set)6 AuthenticationEventExecutionPlan (org.apereo.cas.authentication.AuthenticationEventExecutionPlan)6 AuthenticationHandler (org.apereo.cas.authentication.AuthenticationHandler)6 DefaultPrincipalFactory (org.apereo.cas.authentication.principal.DefaultPrincipalFactory)6 AuthenticationEventExecutionPlanConfigurer (org.apereo.cas.config.support.authentication.AuthenticationEventExecutionPlanConfigurer)6 Qualifier (org.springframework.beans.factory.annotation.Qualifier)6 ConditionalOnMissingBean (org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean)6 RefreshScope (org.springframework.cloud.context.config.annotation.RefreshScope)6 Bean (org.springframework.context.annotation.Bean)6 Configuration (org.springframework.context.annotation.Configuration)6