Search in sources :

Example 11 with IndirectClient

use of org.pac4j.core.client.IndirectClient in project cas by apereo.

the class DefaultDelegatedClientIdentityProviderConfigurationProducer method produce.

@Override
public Set<DelegatedClientIdentityProviderConfiguration> produce(final RequestContext context) {
    val currentService = WebUtils.getService(context);
    val service = authenticationRequestServiceSelectionStrategies.resolveService(currentService, WebApplicationService.class);
    val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(context);
    val response = WebUtils.getHttpServletResponseFromExternalWebflowContext(context);
    val webContext = new JEEContext(request, response);
    LOGGER.debug("Initialized context with request parameters [{}]", webContext.getRequestParameters());
    val allClients = this.clients.findAllClients();
    val providers = new LinkedHashSet<DelegatedClientIdentityProviderConfiguration>(allClients.size());
    allClients.stream().filter(client -> client instanceof IndirectClient && isDelegatedClientAuthorizedForService(client, service, request)).map(IndirectClient.class::cast).forEach(client -> {
        try {
            val providerResult = produce(context, client);
            providerResult.ifPresent(provider -> {
                providers.add(provider);
                delegatedClientIdentityProviderRedirectionStrategy.getPrimaryDelegatedAuthenticationProvider(context, service, provider).ifPresent(p -> WebUtils.putDelegatedAuthenticationProviderPrimary(context, p));
            });
        } catch (final Exception e) {
            LOGGER.error("Cannot process client [{}]", client);
            LoggingUtils.error(LOGGER, e);
        }
    });
    if (!providers.isEmpty()) {
        val selectionType = casProperties.getAuthn().getPac4j().getCore().getDiscoverySelection().getSelectionType();
        switch(selectionType) {
            case DYNAMIC:
                WebUtils.putDelegatedAuthenticationProviderConfigurations(context, new HashSet<>());
                WebUtils.putDelegatedAuthenticationDynamicProviderSelection(context, Boolean.TRUE);
                break;
            case MENU:
            default:
                WebUtils.putDelegatedAuthenticationProviderConfigurations(context, providers);
                WebUtils.putDelegatedAuthenticationDynamicProviderSelection(context, Boolean.FALSE);
                break;
        }
    } else if (response.getStatus() != HttpStatus.UNAUTHORIZED.value()) {
        LOGGER.warn("No delegated authentication providers could be determined based on the provided configuration. " + "Either no clients are configured, or the current access strategy rules prohibit CAS from using authentication providers");
    }
    return providers;
}
Also used : lombok.val(lombok.val) LinkedHashSet(java.util.LinkedHashSet) JEEContext(org.pac4j.core.context.JEEContext) IndirectClient(org.pac4j.core.client.IndirectClient)

Example 12 with IndirectClient

use of org.pac4j.core.client.IndirectClient in project cas by apereo.

the class DefaultDelegatedAuthenticationDynamicDiscoveryProviderLocator method locate.

@Override
public Optional<IndirectClient> locate(final DynamicDiscoveryProviderRequest request) {
    try {
        val resource = casProperties.getAuthn().getPac4j().getCore().getDiscoverySelection().getJson().getLocation();
        val mappings = MAPPER.readValue(resource.getInputStream(), new TypeReference<Map<String, DelegatedAuthenticationDynamicDiscoveryProvider>>() {
        });
        return mappings.entrySet().stream().sorted(Comparator.comparingInt(o -> o.getValue().getOrder())).filter(entry -> RegexUtils.find(entry.getKey(), request.getUserId())).map(Map.Entry::getValue).map(provider -> clients.findClient(provider.getClientName())).flatMap(Optional::stream).map(IndirectClient.class::cast).findFirst();
    } catch (final Exception e) {
        LoggingUtils.error(LOGGER, e);
    }
    return Optional.empty();
}
Also used : lombok.val(lombok.val) CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) Getter(lombok.Getter) DelegatedClientIdentityProviderConfigurationProducer(org.apereo.cas.web.flow.DelegatedClientIdentityProviderConfigurationProducer) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) RequiredArgsConstructor(lombok.RequiredArgsConstructor) lombok.val(lombok.val) RegexUtils(org.apereo.cas.util.RegexUtils) LoggingUtils(org.apereo.cas.util.LoggingUtils) Slf4j(lombok.extern.slf4j.Slf4j) Clients(org.pac4j.core.client.Clients) JacksonObjectMapperFactory(org.apereo.cas.util.serialization.JacksonObjectMapperFactory) Map(java.util.Map) Optional(java.util.Optional) TypeReference(com.fasterxml.jackson.core.type.TypeReference) IndirectClient(org.pac4j.core.client.IndirectClient) Comparator(java.util.Comparator) Optional(java.util.Optional) Map(java.util.Map)

Example 13 with IndirectClient

use of org.pac4j.core.client.IndirectClient in project cas by apereo.

the class DefaultDelegatedClientFactory method configureCasClient.

/**
 * Configure cas client.
 *
 * @param properties the properties
 */
protected void configureCasClient(final Collection<IndirectClient> properties) {
    val pac4jProperties = casProperties.getAuthn().getPac4j();
    val index = new AtomicInteger();
    pac4jProperties.getCas().stream().filter(cas -> cas.isEnabled() && StringUtils.isNotBlank(cas.getLoginUrl())).forEach(cas -> {
        val cfg = new CasConfiguration(cas.getLoginUrl(), CasProtocol.valueOf(cas.getProtocol()));
        val prefix = PATTERN_LOGIN_URL.matcher(cas.getLoginUrl()).replaceFirst("/");
        cfg.setPrefixUrl(StringUtils.appendIfMissing(prefix, "/"));
        cfg.setHostnameVerifier(casSSLContext.getHostnameVerifier());
        cfg.setSslSocketFactory(casSSLContext.getSslContext().getSocketFactory());
        val client = new CasClient(cfg);
        if (StringUtils.isBlank(cas.getClientName())) {
            val count = index.intValue();
            client.setName(client.getClass().getSimpleName() + count);
        }
        configureClient(client, cas);
        index.incrementAndGet();
        LOGGER.debug("Created client [{}]", client);
        properties.add(client);
    });
}
Also used : lombok.val(lombok.val) CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) Pac4jBaseClientProperties(org.apereo.cas.configuration.model.support.pac4j.Pac4jBaseClientProperties) RandomUtils(org.apereo.cas.util.RandomUtils) CasConfiguration(org.pac4j.cas.config.CasConfiguration) CasClient(org.pac4j.cas.client.CasClient) SneakyThrows(lombok.SneakyThrows) Google2Client(org.pac4j.oauth.client.Google2Client) OidcConfiguration(org.pac4j.oidc.config.OidcConfiguration) RequiredArgsConstructor(lombok.RequiredArgsConstructor) SAML2Client(org.pac4j.saml.client.SAML2Client) HttpSessionStoreFactory(org.pac4j.saml.store.HttpSessionStoreFactory) Beans(org.apereo.cas.configuration.support.Beans) StringUtils(org.apache.commons.lang3.StringUtils) PrivateKeyFactoryBean(org.apereo.cas.util.crypto.PrivateKeyFactoryBean) YahooClient(org.pac4j.oauth.client.YahooClient) AzureAdOidcConfiguration(org.pac4j.oidc.config.AzureAdOidcConfiguration) ClassUtils(org.apache.commons.lang3.ClassUtils) FunctionUtils(org.apereo.cas.util.function.FunctionUtils) LinkedIn2Client(org.pac4j.oauth.client.LinkedIn2Client) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HiOrgServerClient(org.pac4j.oauth.client.HiOrgServerClient) IndirectClient(org.pac4j.core.client.IndirectClient) Pac4jOidcClientProperties(org.apereo.cas.configuration.model.support.pac4j.oidc.Pac4jOidcClientProperties) Synchronized(lombok.Synchronized) ResourceUtils(org.apereo.cas.util.ResourceUtils) Unchecked(org.jooq.lambda.Unchecked) Verb(com.github.scribejava.core.model.Verb) Collection(java.util.Collection) Set(java.util.Set) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) BasePac4jOidcClientProperties(org.apereo.cas.configuration.model.support.pac4j.oidc.BasePac4jOidcClientProperties) EmptyStoreFactory(org.pac4j.saml.store.EmptyStoreFactory) Slf4j(lombok.extern.slf4j.Slf4j) ClientCustomPropertyConstants(org.apereo.cas.authentication.principal.ClientCustomPropertyConstants) QueryParameterCallbackUrlResolver(org.pac4j.core.http.callback.QueryParameterCallbackUrlResolver) XMLSecSAML2MetadataSigner(org.pac4j.saml.metadata.XMLSecSAML2MetadataSigner) DisposableBean(org.springframework.beans.factory.DisposableBean) CasSSLContext(org.apereo.cas.authentication.CasSSLContext) CasWebflowConfigurer(org.apereo.cas.web.flow.CasWebflowConfigurer) CasProtocol(org.pac4j.cas.config.CasProtocol) FoursquareClient(org.pac4j.oauth.client.FoursquareClient) GitHubClient(org.pac4j.oauth.client.GitHubClient) SAML2Configuration(org.pac4j.saml.config.SAML2Configuration) Pattern(java.util.regex.Pattern) PathParameterCallbackUrlResolver(org.pac4j.core.http.callback.PathParameterCallbackUrlResolver) WindowsLiveClient(org.pac4j.oauth.client.WindowsLiveClient) AzureAdClient(org.pac4j.oidc.client.AzureAdClient) Getter(lombok.Getter) BitbucketClient(org.pac4j.oauth.client.BitbucketClient) WordPressClient(org.pac4j.oauth.client.WordPressClient) SAML2ServiceProviderRequestedAttribute(org.pac4j.saml.metadata.SAML2ServiceProviderRequestedAttribute) OidcClient(org.pac4j.oidc.client.OidcClient) CollectionUtils(org.apereo.cas.util.CollectionUtils) PayPalClient(org.pac4j.oauth.client.PayPalClient) ECPrivateKey(java.security.interfaces.ECPrivateKey) LinkedHashSet(java.util.LinkedHashSet) NoParameterCallbackUrlResolver(org.pac4j.core.http.callback.NoParameterCallbackUrlResolver) Period(java.time.Period) GoogleOidcClient(org.pac4j.oidc.client.GoogleOidcClient) FacebookClient(org.pac4j.oauth.client.FacebookClient) KeycloakOidcClient(org.pac4j.oidc.client.KeycloakOidcClient) lombok.val(lombok.val) ApplicationContext(org.springframework.context.ApplicationContext) AppleOidcConfiguration(org.pac4j.oidc.config.AppleOidcConfiguration) GenericOAuth20Client(org.pac4j.oauth.client.GenericOAuth20Client) AppleClient(org.pac4j.oidc.client.AppleClient) TwitterClient(org.pac4j.oauth.client.TwitterClient) SAMLMessageStoreFactory(org.pac4j.saml.store.SAMLMessageStoreFactory) KeycloakOidcConfiguration(org.pac4j.oidc.config.KeycloakOidcConfiguration) DropBoxClient(org.pac4j.oauth.client.DropBoxClient) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CasConfiguration(org.pac4j.cas.config.CasConfiguration) CasClient(org.pac4j.cas.client.CasClient)

Example 14 with IndirectClient

use of org.pac4j.core.client.IndirectClient in project cas by apereo.

the class BaseDelegatedAuthenticationController method getRedirectionAction.

/**
 * Gets redirection action.
 *
 * @param client     the client
 * @param webContext the web context
 * @param ticket     the ticket
 * @return the redirection action
 */
protected Optional<RedirectionAction> getRedirectionAction(final IndirectClient client, final WebContext webContext, final TransientSessionTicket ticket) {
    val properties = ticket.getProperties();
    if (properties.containsKey(RedirectionActionBuilder.ATTRIBUTE_FORCE_AUTHN)) {
        webContext.setRequestAttribute(RedirectionActionBuilder.ATTRIBUTE_FORCE_AUTHN, true);
    }
    if (properties.containsKey(RedirectionActionBuilder.ATTRIBUTE_PASSIVE)) {
        webContext.setRequestAttribute(RedirectionActionBuilder.ATTRIBUTE_PASSIVE, true);
    }
    if (ticket.getService() != null) {
        configureWebContextForRegisteredService(webContext, ticket);
    }
    configurationContext.getDelegatedClientAuthenticationRequestCustomizers().stream().sorted(AnnotationAwareOrderComparator.INSTANCE).filter(c -> c.supports(client, webContext)).forEach(c -> c.customize(client, webContext));
    return client.getRedirectionActionBuilder().getRedirectionAction(webContext, configurationContext.getSessionStore());
}
Also used : lombok.val(lombok.val) Arrays(java.util.Arrays) Getter(lombok.Getter) RegisteredServiceProperties(org.apereo.cas.services.RegisteredServiceProperty.RegisteredServiceProperties) RegisteredServicePropertyGroups(org.apereo.cas.services.RegisteredServiceProperty.RegisteredServicePropertyGroups) RequiredArgsConstructor(lombok.RequiredArgsConstructor) Controller(org.springframework.stereotype.Controller) Pac4jConstants(org.pac4j.core.util.Pac4jConstants) WebContext(org.pac4j.core.context.WebContext) HttpServletRequest(javax.servlet.http.HttpServletRequest) AccessLevel(lombok.AccessLevel) DynamicHtmlView(org.apereo.cas.web.view.DynamicHtmlView) RedirectView(org.springframework.web.servlet.view.RedirectView) IndirectClient(org.pac4j.core.client.IndirectClient) RedirectionActionBuilder(org.pac4j.core.redirect.RedirectionActionBuilder) TransientSessionTicket(org.apereo.cas.ticket.TransientSessionTicket) AuditableContext(org.apereo.cas.audit.AuditableContext) URIBuilder(org.apache.http.client.utils.URIBuilder) lombok.val(lombok.val) WithLocationAction(org.pac4j.core.exception.http.WithLocationAction) Collectors(java.util.stream.Collectors) RegisteredService(org.apereo.cas.services.RegisteredService) Slf4j(lombok.extern.slf4j.Slf4j) View(org.springframework.web.servlet.View) List(java.util.List) DelegatedClientAuthenticationConfigurationContext(org.apereo.cas.web.flow.DelegatedClientAuthenticationConfigurationContext) Optional(java.util.Optional) RedirectionAction(org.pac4j.core.exception.http.RedirectionAction) WithContentAction(org.pac4j.core.exception.http.WithContentAction) AnnotationAwareOrderComparator(org.springframework.core.annotation.AnnotationAwareOrderComparator)

Example 15 with IndirectClient

use of org.pac4j.core.client.IndirectClient in project pac4j by pac4j.

the class DefaultCallbackLogicTests method testCallback.

@Test
public void testCallback() {
    final var originalSessionId = sessionStore.getSessionId(context, false);
    context.addRequestParameter(Pac4jConstants.DEFAULT_CLIENT_NAME_PARAMETER, NAME);
    final var profile = new CommonProfile();
    final IndirectClient indirectClient = new MockIndirectClient(NAME, null, Optional.of(new MockCredentials()), profile);
    config.setClients(new Clients(CALLBACK_URL, indirectClient));
    call();
    final var newSessionId = sessionStore.getSessionId(context, false);
    final var profiles = (LinkedHashMap<String, CommonProfile>) sessionStore.get(context, Pac4jConstants.USER_PROFILES).get();
    assertTrue(profiles.containsValue(profile));
    assertEquals(1, profiles.size());
    assertNotEquals(newSessionId, originalSessionId);
    assertEquals(302, action.getCode());
    assertEquals(Pac4jConstants.DEFAULT_URL_VALUE, ((FoundAction) action).getLocation());
}
Also used : CommonProfile(org.pac4j.core.profile.CommonProfile) MockIndirectClient(org.pac4j.core.client.MockIndirectClient) MockCredentials(org.pac4j.core.credentials.MockCredentials) IndirectClient(org.pac4j.core.client.IndirectClient) MockIndirectClient(org.pac4j.core.client.MockIndirectClient) Clients(org.pac4j.core.client.Clients) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.Test)

Aggregations

IndirectClient (org.pac4j.core.client.IndirectClient)15 LinkedHashSet (java.util.LinkedHashSet)7 lombok.val (lombok.val)7 RequiredArgsConstructor (lombok.RequiredArgsConstructor)6 Slf4j (lombok.extern.slf4j.Slf4j)6 Clients (org.pac4j.core.client.Clients)6 Getter (lombok.Getter)5 CasConfigurationProperties (org.apereo.cas.configuration.CasConfigurationProperties)5 LinkedHashMap (java.util.LinkedHashMap)4 Set (java.util.Set)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 MockIndirectClient (org.pac4j.core.client.MockIndirectClient)4 Verb (com.github.scribejava.core.model.Verb)3 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)3 ECPrivateKey (java.security.interfaces.ECPrivateKey)3 Period (java.time.Period)3 Collection (java.util.Collection)3 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 Pattern (java.util.regex.Pattern)3 Optional (java.util.Optional)2