Search in sources :

Example 16 with J2EContext

use of org.pac4j.core.context.J2EContext in project cas by apereo.

the class OidcIdTokenGeneratorService method generate.

/**
 * Generate string.
 *
 * @param request           the request
 * @param response          the response
 * @param accessTokenId     the access token id
 * @param timeout           the timeout
 * @param responseType      the response type
 * @param registeredService the registered service
 * @return the string
 * @throws Exception the exception
 */
public String generate(final HttpServletRequest request, final HttpServletResponse response, final AccessToken accessTokenId, final long timeout, final OAuth20ResponseTypes responseType, final OAuthRegisteredService registeredService) throws Exception {
    if (!(registeredService instanceof OidcRegisteredService)) {
        throw new IllegalArgumentException("Registered service instance is not an OIDC service");
    }
    final OidcRegisteredService oidcRegisteredService = (OidcRegisteredService) registeredService;
    final J2EContext context = Pac4jUtils.getPac4jJ2EContext(request, response);
    final ProfileManager manager = Pac4jUtils.getPac4jProfileManager(request, response);
    final Optional<UserProfile> profile = manager.get(true);
    LOGGER.debug("Attempting to produce claims for the id token [{}]", accessTokenId);
    final JwtClaims claims = produceIdTokenClaims(request, accessTokenId, timeout, oidcRegisteredService, profile.get(), context, responseType);
    LOGGER.debug("Produce claims for the id token [{}] as [{}]", accessTokenId, claims);
    return this.signingService.encode(oidcRegisteredService, claims);
}
Also used : ProfileManager(org.pac4j.core.profile.ProfileManager) UserProfile(org.pac4j.core.profile.UserProfile) JwtClaims(org.jose4j.jwt.JwtClaims) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) J2EContext(org.pac4j.core.context.J2EContext)

Example 17 with J2EContext

use of org.pac4j.core.context.J2EContext in project cas by apereo.

the class OidcSecurityInterceptor method preHandle.

@Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
    final J2EContext ctx = Pac4jUtils.getPac4jJ2EContext(request, response);
    final ProfileManager manager = Pac4jUtils.getPac4jProfileManager(request, response);
    boolean clearCreds = false;
    final Optional<Authentication> authentication = authorizationRequestSupport.isCasAuthenticationAvailable(ctx);
    if (!authentication.isPresent()) {
        clearCreds = true;
    }
    final Optional<UserProfile> auth = authorizationRequestSupport.isAuthenticationProfileAvailable(ctx);
    if (auth.isPresent()) {
        final Optional<Long> maxAge = authorizationRequestSupport.getOidcMaxAgeFromAuthorizationRequest(ctx);
        if (maxAge.isPresent()) {
            clearCreds = authorizationRequestSupport.isCasAuthenticationOldForMaxAgeAuthorizationRequest(ctx, auth.get());
        }
    }
    final Set<String> prompts = authorizationRequestSupport.getOidcPromptFromAuthorizationRequest(ctx);
    if (!clearCreds) {
        clearCreds = prompts.contains(OidcConstants.PROMPT_LOGIN);
    }
    if (clearCreds) {
        clearCreds = !prompts.contains(OidcConstants.PROMPT_NONE);
    }
    if (clearCreds) {
        manager.remove(true);
    }
    return super.preHandle(request, response, handler);
}
Also used : ProfileManager(org.pac4j.core.profile.ProfileManager) UserProfile(org.pac4j.core.profile.UserProfile) Authentication(org.apereo.cas.authentication.Authentication) J2EContext(org.pac4j.core.context.J2EContext)

Example 18 with J2EContext

use of org.pac4j.core.context.J2EContext 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 19 with J2EContext

use of org.pac4j.core.context.J2EContext in project cas by apereo.

the class DelegatedClientAuthenticationAction method doExecute.

@Override
protected Event doExecute(final RequestContext context) {
    final HttpServletRequest request = WebUtils.getHttpServletRequestFromExternalWebflowContext(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponseFromExternalWebflowContext(context);
    final String clientName = request.getParameter(Pac4jConstants.DEFAULT_CLIENT_NAME_PARAMETER);
    LOGGER.debug("Delegated authentication is handled by client name [{}]", clientName);
    if (hasDelegationRequestFailed(request, response.getStatus()).isPresent()) {
        return stopWebflow();
    }
    final J2EContext webContext = Pac4jUtils.getPac4jJ2EContext(request, response);
    if (StringUtils.isNotBlank(clientName)) {
        final Service service = restoreAuthenticationRequestInContext(context, webContext, clientName);
        final BaseClient<Credentials, CommonProfile> client = findDelegatedClientByName(request, clientName, service);
        final Credentials credentials;
        try {
            credentials = client.getCredentials(webContext);
            LOGGER.debug("Retrieved credentials from client as [{}]", credentials);
            if (credentials == null) {
                throw new IllegalArgumentException("Unable to determine credentials from the context with client " + client.getName());
            }
        } catch (final Exception e) {
            LOGGER.debug(e.getMessage(), e);
            return stopWebflow();
        }
        if (credentials != null) {
            return establishDelegatedAuthenticationSession(context, service, credentials, client);
        }
    }
    prepareForLoginPage(context);
    if (response.getStatus() == HttpStatus.UNAUTHORIZED.value()) {
        return stopWebflow();
    }
    return error();
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) CommonProfile(org.pac4j.core.profile.CommonProfile) HttpServletResponse(javax.servlet.http.HttpServletResponse) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) ToString(lombok.ToString) J2EContext(org.pac4j.core.context.J2EContext) Credentials(org.pac4j.core.credentials.Credentials) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException)

Example 20 with J2EContext

use of org.pac4j.core.context.J2EContext 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)

Aggregations

J2EContext (org.pac4j.core.context.J2EContext)32 RedirectAction (org.pac4j.core.redirect.RedirectAction)13 Test (org.junit.Test)11 WebContext (org.pac4j.core.context.WebContext)11 ProfileManager (org.pac4j.core.profile.ProfileManager)11 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)11 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)11 HttpServletRequest (javax.servlet.http.HttpServletRequest)6 HttpServletResponse (javax.servlet.http.HttpServletResponse)6 UnauthorizedServiceException (org.apereo.cas.services.UnauthorizedServiceException)6 OAuthRegisteredService (org.apereo.cas.support.oauth.services.OAuthRegisteredService)6 UserProfile (org.pac4j.core.profile.UserProfile)6 GetMapping (org.springframework.web.bind.annotation.GetMapping)6 Service (org.apereo.cas.authentication.principal.Service)5 Authentication (org.apereo.cas.authentication.Authentication)4 AccessToken (org.apereo.cas.ticket.accesstoken.AccessToken)4 TicketGrantingTicket (org.apereo.cas.ticket.TicketGrantingTicket)3 CentralAuthenticationService (org.apereo.cas.CentralAuthenticationService)2 AuthenticationResult (org.apereo.cas.authentication.AuthenticationResult)2 PrincipalException (org.apereo.cas.authentication.PrincipalException)2