Search in sources :

Example 11 with SAML2Client

use of org.pac4j.saml.client.SAML2Client in project cas by apereo.

the class DelegatedClientFactory method configureSamlClient.

/**
 * Configure saml client.
 *
 * @param properties the properties
 */
protected void configureSamlClient(final Collection<BaseClient> properties) {
    final AtomicInteger index = new AtomicInteger();
    pac4jProperties.getSaml().stream().filter(saml -> StringUtils.isNotBlank(saml.getKeystorePath()) && StringUtils.isNotBlank(saml.getIdentityProviderMetadataPath()) && StringUtils.isNotBlank(saml.getServiceProviderEntityId()) && StringUtils.isNotBlank(saml.getServiceProviderMetadataPath())).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(saml.getDestinationBinding());
        cfg.setForceAuth(saml.isForceAuth());
        cfg.setPassive(saml.isPassive());
        cfg.setWantsAssertionsSigned(saml.isWantsAssertionsSigned());
        cfg.setAttributeConsumingServiceIndex(saml.getAttributeConsumingServiceIndex());
        if (saml.getAssertionConsumerServiceIndex() >= 0) {
            cfg.setAssertionConsumerServiceIndex(saml.getAssertionConsumerServiceIndex());
        }
        if (StringUtils.isNotBlank(saml.getAuthnContextClassRef())) {
            cfg.setComparisonType(saml.getAuthnContextComparisonType().toUpperCase());
            cfg.setAuthnContextClassRef(saml.getAuthnContextClassRef());
        }
        if (StringUtils.isNotBlank(saml.getKeystoreAlias())) {
            cfg.setKeystoreAlias(saml.getKeystoreAlias());
        }
        if (StringUtils.isNotBlank(saml.getNameIdPolicyFormat())) {
            cfg.setNameIdPolicyFormat(saml.getNameIdPolicyFormat());
        }
        final SAML2Client client = new SAML2Client(cfg);
        final int count = index.intValue();
        if (StringUtils.isBlank(saml.getClientName())) {
            client.setName(client.getClass().getSimpleName() + count);
        }
        configureClient(client, saml);
        index.incrementAndGet();
        LOGGER.debug("Created delegated client [{}]", client);
        properties.add(client);
    });
}
Also used : Pac4jBaseClientProperties(org.apereo.cas.configuration.model.support.pac4j.Pac4jBaseClientProperties) WindowsLiveClient(org.pac4j.oauth.client.WindowsLiveClient) AzureAdClient(org.pac4j.oidc.client.AzureAdClient) CasConfiguration(org.pac4j.cas.config.CasConfiguration) CasClient(org.pac4j.cas.client.CasClient) BitbucketClient(org.pac4j.oauth.client.BitbucketClient) SneakyThrows(lombok.SneakyThrows) Google2Client(org.pac4j.oauth.client.Google2Client) OidcConfiguration(org.pac4j.oidc.config.OidcConfiguration) RequiredArgsConstructor(lombok.RequiredArgsConstructor) SAML2Client(org.pac4j.saml.client.SAML2Client) WordPressClient(org.pac4j.oauth.client.WordPressClient) StringUtils(org.apache.commons.lang3.StringUtils) YahooClient(org.pac4j.oauth.client.YahooClient) AzureAdOidcConfiguration(org.pac4j.oidc.config.AzureAdOidcConfiguration) LinkedIn2Client(org.pac4j.oauth.client.LinkedIn2Client) OidcClient(org.pac4j.oidc.client.OidcClient) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) PayPalClient(org.pac4j.oauth.client.PayPalClient) LinkedHashSet(java.util.LinkedHashSet) GoogleOidcClient(org.pac4j.oidc.client.GoogleOidcClient) FacebookClient(org.pac4j.oauth.client.FacebookClient) KeycloakOidcClient(org.pac4j.oidc.client.KeycloakOidcClient) Verb(com.github.scribejava.core.model.Verb) Collection(java.util.Collection) Pac4jDelegatedAuthenticationProperties(org.apereo.cas.configuration.model.support.pac4j.Pac4jDelegatedAuthenticationProperties) Set(java.util.Set) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) GenericOAuth20Client(org.pac4j.oauth.client.GenericOAuth20Client) Slf4j(lombok.extern.slf4j.Slf4j) BaseClient(org.pac4j.core.client.BaseClient) TwitterClient(org.pac4j.oauth.client.TwitterClient) Pac4jOidcProperties(org.apereo.cas.configuration.model.support.pac4j.Pac4jOidcProperties) KeycloakOidcConfiguration(org.pac4j.oidc.config.KeycloakOidcConfiguration) CasProtocol(org.pac4j.cas.config.CasProtocol) FoursquareClient(org.pac4j.oauth.client.FoursquareClient) GitHubClient(org.pac4j.oauth.client.GitHubClient) OrcidClient(org.pac4j.oauth.client.OrcidClient) DropBoxClient(org.pac4j.oauth.client.DropBoxClient) SAML2ClientConfiguration(org.pac4j.saml.client.SAML2ClientConfiguration) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SAML2Client(org.pac4j.saml.client.SAML2Client) SAML2ClientConfiguration(org.pac4j.saml.client.SAML2ClientConfiguration)

Example 12 with SAML2Client

use of org.pac4j.saml.client.SAML2Client in project cas by apereo.

the class SAML2ClientLogoutAction method doExecute.

@Override
protected Event doExecute(final RequestContext requestContext) {
    try {
        final HttpServletRequest request = WebUtils.getHttpServletRequestFromExternalWebflowContext(requestContext);
        final HttpServletResponse response = WebUtils.getHttpServletResponseFromExternalWebflowContext(requestContext);
        final J2EContext context = Pac4jUtils.getPac4jJ2EContext(request, response);
        Client<?, ?> client;
        try {
            final String currentClientName = findCurrentClientName(context);
            client = (currentClientName == null) ? null : clients.findClient(currentClientName);
        } catch (final TechnicalException e) {
            LOGGER.debug("No SAML2 client found: " + e.getMessage(), e);
            client = null;
        }
        if (client instanceof SAML2Client) {
            final SAML2Client saml2Client = (SAML2Client) client;
            LOGGER.debug("Located SAML2 client [{}]", saml2Client);
            final RedirectAction action = saml2Client.getLogoutAction(context, null, null);
            LOGGER.debug("Preparing logout message to send is [{}]", action.getLocation());
            action.perform(context);
        } else {
            LOGGER.debug("The current client is not a SAML2 client or it cannot be found at all, no logout action will be executed.");
        }
    } catch (final Exception e) {
        LOGGER.warn(e.getMessage(), e);
    }
    return null;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) TechnicalException(org.pac4j.core.exception.TechnicalException) HttpServletResponse(javax.servlet.http.HttpServletResponse) SAML2Client(org.pac4j.saml.client.SAML2Client) J2EContext(org.pac4j.core.context.J2EContext) TechnicalException(org.pac4j.core.exception.TechnicalException) RedirectAction(org.pac4j.core.redirect.RedirectAction)

Example 13 with SAML2Client

use of org.pac4j.saml.client.SAML2Client in project pac4j by pac4j.

the class RunTestshib method getClient.

@Override
protected IndirectClient getClient() {
    final SAML2ClientConfiguration cfg = new SAML2ClientConfiguration(new ClassPathResource("samlKeystore.jks"), "pac4j-demo-passwd", "pac4j-demo-passwd", new ClassPathResource("testshib-providers.xml"));
    cfg.setMaximumAuthenticationLifetime(3600);
    cfg.setServiceProviderEntityId("urn:mace:saml:pac4j.org");
    cfg.setServiceProviderMetadataResource(new FileSystemResource(new File("target", "test-sp-metadata.xml").getAbsolutePath()));
    cfg.setDestinationBindingType(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
    final SAML2Client client = new SAML2Client(cfg);
    client.setCallbackUrl(PAC4J_URL);
    return client;
}
Also used : SAML2Client(org.pac4j.saml.client.SAML2Client) SAML2ClientConfiguration(org.pac4j.saml.client.SAML2ClientConfiguration) FileSystemResource(org.springframework.core.io.FileSystemResource) File(java.io.File) ClassPathResource(org.springframework.core.io.ClassPathResource)

Example 14 with SAML2Client

use of org.pac4j.saml.client.SAML2Client in project cas by apereo.

the class SamlIdPDelegatedClientAuthenticationRequestCustomizer method isAuthorized.

@Override
public boolean isAuthorized(final JEEContext webContext, final IndirectClient client, final WebApplicationService currentService) {
    val result = SamlIdPUtils.retrieveSamlRequest(webContext, sessionStore, openSamlConfigBean, AuthnRequest.class);
    if (result.isEmpty()) {
        LOGGER.trace("No SAML2 authentication request found in session store");
        return true;
    }
    val authnRequest = (AuthnRequest) result.get().getLeft();
    LOGGER.trace("Retrieved the SAML2 authentication request from [{}]", SamlIdPUtils.getIssuerFromSamlObject(authnRequest));
    val idpList = authnRequest.getScoping() != null ? authnRequest.getScoping().getIDPList() : null;
    val idpEntries = idpList != null && idpList.getIDPEntrys() != null ? idpList.getIDPEntrys() : List.<IDPEntry>of();
    val providerList = idpEntries.stream().map(IDPEntry::getProviderID).collect(Collectors.toList());
    LOGGER.debug("Scoped identity providers are [{}] to examine against client [{}]", providerList, client.getName());
    if (supports(client, webContext)) {
        val saml2Client = (SAML2Client) client;
        LOGGER.debug("Comparing [{}] against scoped identity providers [{}]", saml2Client.getIdentityProviderResolvedEntityId(), providerList);
        return providerList.isEmpty() || providerList.contains(saml2Client.getIdentityProviderResolvedEntityId());
    }
    return true;
}
Also used : lombok.val(lombok.val) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) SAML2Client(org.pac4j.saml.client.SAML2Client)

Example 15 with SAML2Client

use of org.pac4j.saml.client.SAML2Client in project cas by apereo.

the class SamlIdentityProviderDiscoveryConfiguration method samlIdentityProviderEntityParser.

@Bean
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)
@ConditionalOnMissingBean(name = "samlIdentityProviderEntityParser")
public Supplier<List<SamlIdentityProviderEntityParser>> samlIdentityProviderEntityParser(final CasConfigurationProperties casProperties, @Qualifier("builtClients") final Clients builtClients) {
    val parsers = new ArrayList<SamlIdentityProviderEntityParser>();
    val resource = casProperties.getAuthn().getPac4j().getSamlDiscovery().getResource();
    resource.stream().filter(res -> res.getLocation() != null).forEach(Unchecked.consumer(res -> parsers.add(new SamlIdentityProviderEntityParser(res.getLocation()))));
    builtClients.findAllClients().stream().filter(c -> c instanceof SAML2Client).map(SAML2Client.class::cast).forEach(c -> {
        c.init();
        val entity = new SamlIdentityProviderEntity();
        entity.setEntityID(c.getIdentityProviderResolvedEntityId());
        parsers.add(new SamlIdentityProviderEntityParser(entity));
    });
    return () -> parsers;
}
Also used : lombok.val(lombok.val) CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) ArgumentExtractor(org.apereo.cas.web.support.ArgumentExtractor) SAML2Client(org.pac4j.saml.client.SAML2Client) FlowBuilderServices(org.springframework.webflow.engine.builder.support.FlowBuilderServices) Supplier(java.util.function.Supplier) RefreshScope(org.springframework.cloud.context.config.annotation.RefreshScope) ArrayList(java.util.ArrayList) Clients(org.pac4j.core.client.Clients) CasWebflowConstants(org.apereo.cas.web.flow.CasWebflowConstants) EnableConfigurationProperties(org.springframework.boot.context.properties.EnableConfigurationProperties) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) Qualifier(org.springframework.beans.factory.annotation.Qualifier) ServicesManager(org.apereo.cas.services.ServicesManager) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) Unchecked(org.jooq.lambda.Unchecked) FlowDefinitionRegistry(org.springframework.webflow.definition.registry.FlowDefinitionRegistry) lombok.val(lombok.val) ScopedProxyMode(org.springframework.context.annotation.ScopedProxyMode) ConditionalOnFeature(org.apereo.cas.util.spring.boot.ConditionalOnFeature) SamlIdentityProviderEntity(org.apereo.cas.entity.SamlIdentityProviderEntity) Configuration(org.springframework.context.annotation.Configuration) SamlIdentityProviderDiscoveryWebflowConfigurer(org.apereo.cas.web.flow.SamlIdentityProviderDiscoveryWebflowConfigurer) List(java.util.List) AuditableExecution(org.apereo.cas.audit.AuditableExecution) CasFeatureModule(org.apereo.cas.configuration.support.CasFeatureModule) SamlIdentityProviderDiscoveryFeedController(org.apereo.cas.web.SamlIdentityProviderDiscoveryFeedController) DelegatedAuthenticationAccessStrategyHelper(org.apereo.cas.validation.DelegatedAuthenticationAccessStrategyHelper) CasWebflowConfigurer(org.apereo.cas.web.flow.CasWebflowConfigurer) SamlIdentityProviderEntityParser(org.apereo.cas.entity.SamlIdentityProviderEntityParser) Bean(org.springframework.context.annotation.Bean) CasWebflowExecutionPlanConfigurer(org.apereo.cas.web.flow.CasWebflowExecutionPlanConfigurer) ArrayList(java.util.ArrayList) SAML2Client(org.pac4j.saml.client.SAML2Client) SamlIdentityProviderEntityParser(org.apereo.cas.entity.SamlIdentityProviderEntityParser) SamlIdentityProviderEntity(org.apereo.cas.entity.SamlIdentityProviderEntity) RefreshScope(org.springframework.cloud.context.config.annotation.RefreshScope) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) Bean(org.springframework.context.annotation.Bean)

Aggregations

SAML2Client (org.pac4j.saml.client.SAML2Client)24 lombok.val (lombok.val)16 Test (org.junit.jupiter.api.Test)6 CasClient (org.pac4j.cas.client.CasClient)6 OidcClient (org.pac4j.oidc.client.OidcClient)6 SAML2Configuration (org.pac4j.saml.config.SAML2Configuration)6 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)6 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)6 SAML2ClientConfiguration (org.pac4j.saml.client.SAML2ClientConfiguration)5 File (java.io.File)4 Collection (java.util.Collection)4 Set (java.util.Set)4 StringUtils (org.apache.commons.lang3.StringUtils)4 CasConfigurationProperties (org.apereo.cas.configuration.CasConfigurationProperties)4 MockServletContext (org.apereo.cas.util.MockServletContext)4 Clients (org.pac4j.core.client.Clients)4 JEEContext (org.pac4j.core.context.JEEContext)4 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)4 Verb (com.github.scribejava.core.model.Verb)3 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)3