Search in sources :

Example 6 with IndirectClient

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

the class DefaultCallbackLogicTests method internalTestCallbackWithOriginallyRequestedUrl.

private void internalTestCallbackWithOriginallyRequestedUrl(final int code) {
    final var originalSessionId = sessionStore.getSessionId(context, false);
    sessionStore.set(context, Pac4jConstants.REQUESTED_URL, new FoundAction(PAC4J_URL));
    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(code, action.getCode());
    if (action instanceof SeeOtherAction) {
        assertEquals(PAC4J_URL, ((SeeOtherAction) action).getLocation());
    } else {
        assertEquals(PAC4J_URL, ((FoundAction) action).getLocation());
    }
}
Also used : FoundAction(org.pac4j.core.exception.http.FoundAction) 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) SeeOtherAction(org.pac4j.core.exception.http.SeeOtherAction) Clients(org.pac4j.core.client.Clients) LinkedHashMap(java.util.LinkedHashMap)

Example 7 with IndirectClient

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

the class DelegatedClientNavigationController method redirectToProvider.

/**
 * Redirect to provider. Receive the client name from the request and then try to determine and build the endpoint url
 * for the redirection. The redirection data/url must contain a delegated client ticket id so that the request be can
 * restored on the trip back. SAML clients use the relay-state session attribute while others use request parameters.
 *
 * @param request  the request
 * @param response the response
 * @return the view
 */
@GetMapping(ENDPOINT_REDIRECT)
public View redirectToProvider(final HttpServletRequest request, final HttpServletResponse response) {
    final String clientName = request.getParameter(Pac4jConstants.DEFAULT_CLIENT_NAME_PARAMETER);
    try {
        final IndirectClient client = (IndirectClient<Credentials, CommonProfile>) this.clients.findClient(clientName);
        final J2EContext webContext = Pac4jUtils.getPac4jJ2EContext(request, response);
        final Ticket ticket = delegatedClientWebflowManager.store(webContext, client);
        final View result;
        final RedirectAction action = client.getRedirectAction(webContext);
        if (RedirectAction.RedirectType.SUCCESS.equals(action.getType())) {
            result = new DynamicHtmlView(action.getContent());
        } else {
            final URIBuilder builder = new URIBuilder(action.getLocation());
            final String url = builder.toString();
            LOGGER.debug("Redirecting client [{}] to [{}] based on identifier [{}]", client.getName(), url, ticket.getId());
            result = new RedirectView(url);
        }
        this.delegatedSessionCookieManager.store(webContext);
        return result;
    } catch (final HttpAction e) {
        if (e.getCode() == HttpStatus.UNAUTHORIZED.value()) {
            LOGGER.debug("Authentication request was denied from the provider [{}]", clientName, e);
        } else {
            LOGGER.warn(e.getMessage(), e);
        }
        throw new UnauthorizedServiceException(e.getMessage(), e);
    }
}
Also used : Ticket(org.apereo.cas.ticket.Ticket) RedirectView(org.springframework.web.servlet.view.RedirectView) IndirectClient(org.pac4j.core.client.IndirectClient) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) J2EContext(org.pac4j.core.context.J2EContext) View(org.springframework.web.servlet.View) DynamicHtmlView(org.apereo.cas.web.view.DynamicHtmlView) RedirectView(org.springframework.web.servlet.view.RedirectView) DynamicHtmlView(org.apereo.cas.web.view.DynamicHtmlView) HttpAction(org.pac4j.core.exception.HttpAction) RedirectAction(org.pac4j.core.redirect.RedirectAction) URIBuilder(org.jasig.cas.client.util.URIBuilder) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 8 with IndirectClient

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

the class DelegatedClientAuthenticationAction method prepareForLoginPage.

/**
 * Prepare the data for the login page.
 *
 * @param context The current webflow context
 */
protected void prepareForLoginPage(final RequestContext context) {
    final Service service = WebUtils.getService(context);
    final HttpServletRequest request = WebUtils.getHttpServletRequestFromExternalWebflowContext(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponseFromExternalWebflowContext(context);
    final WebContext webContext = Pac4jUtils.getPac4jJ2EContext(request, response);
    final Set<ProviderLoginPageConfiguration> urls = new LinkedHashSet<>();
    this.clients.findAllClients().stream().filter(client -> client instanceof IndirectClient && isDelegatedClientAuthorizedForService(client, service)).map(IndirectClient.class::cast).forEach(client -> {
        try {
            final Optional<ProviderLoginPageConfiguration> provider = buildProviderConfiguration(client, webContext);
            provider.ifPresent(urls::add);
        } catch (final Exception e) {
            LOGGER.error("Cannot process client [{}]", client, e);
        }
    });
    if (!urls.isEmpty()) {
        context.getFlowScope().put(PAC4J_URLS, urls);
    } 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 for this request.");
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) LinkedHashSet(java.util.LinkedHashSet) WebContext(org.pac4j.core.context.WebContext) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) HttpServletResponse(javax.servlet.http.HttpServletResponse) IndirectClient(org.pac4j.core.client.IndirectClient) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException)

Example 9 with IndirectClient

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

the class DefaultCallbackClientFinder method find.

public List<Client> find(final Clients clients, final WebContext context, final String clientNames) {
    final List<Client> result = new ArrayList<>();
    final List<Client> indirectClients = new ArrayList<>();
    for (final Client client : clients.findAllClients()) {
        if (client instanceof IndirectClient) {
            final IndirectClient indirectClient = (IndirectClient) client;
            indirectClients.add(client);
            indirectClient.init();
            if (indirectClient.getCallbackUrlResolver().matches(indirectClient.getName(), context)) {
                result.add(indirectClient);
            }
        }
    }
    logger.debug("result: {}", result.stream().map(c -> c.getName()).collect(Collectors.toList()));
    // fallback: we didn't find any client on the URL
    if (result.isEmpty()) {
        // we have a default client, use it
        if (CommonHelper.isNotBlank(clientNames)) {
            final Client defaultClient = clients.findClient(clientNames);
            logger.debug("Defaulting to the configured client: {}", defaultClient);
            result.add(defaultClient);
        // or we only have one indirect client, use it
        } else if (indirectClients.size() == 1) {
            logger.debug("Defaulting to the only client: {}", indirectClients.get(0));
            result.addAll(indirectClients);
        }
    }
    return result;
}
Also used : ArrayList(java.util.ArrayList) IndirectClient(org.pac4j.core.client.IndirectClient) Client(org.pac4j.core.client.Client) IndirectClient(org.pac4j.core.client.IndirectClient)

Example 10 with IndirectClient

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

the class DefaultCallbackLogicTests method testCallbackWithOriginallyRequestedUrl.

@Test
public void testCallbackWithOriginallyRequestedUrl() {
    HttpSession session = request.getSession();
    final String originalSessionId = session.getId();
    session.setAttribute(Pac4jConstants.REQUESTED_URL, PAC4J_URL);
    request.setParameter(Pac4jConstants.DEFAULT_CLIENT_NAME_PARAMETER, NAME);
    final CommonProfile profile = new CommonProfile();
    final IndirectClient indirectClient = new MockIndirectClient(NAME, null, new MockCredentials(), profile);
    config.setClients(new Clients(CALLBACK_URL, indirectClient));
    config.getClients().init();
    call();
    session = request.getSession();
    final String newSessionId = session.getId();
    final LinkedHashMap<String, CommonProfile> profiles = (LinkedHashMap<String, CommonProfile>) session.getAttribute(Pac4jConstants.USER_PROFILES);
    assertTrue(profiles.containsValue(profile));
    assertEquals(1, profiles.size());
    assertNotEquals(newSessionId, originalSessionId);
    assertEquals(302, response.getStatus());
    assertEquals(PAC4J_URL, response.getRedirectedUrl());
}
Also used : CommonProfile(org.pac4j.core.profile.CommonProfile) MockIndirectClient(org.pac4j.core.client.MockIndirectClient) MockCredentials(org.pac4j.core.credentials.MockCredentials) HttpSession(javax.servlet.http.HttpSession) MockIndirectClient(org.pac4j.core.client.MockIndirectClient) IndirectClient(org.pac4j.core.client.IndirectClient) 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