Search in sources :

Example 6 with AbstractTicketException

use of org.apereo.cas.ticket.AbstractTicketException in project cas by apereo.

the class AbstractServiceValidateController method handleTicketValidation.

/**
 * Handle ticket validation model and view.
 *
 * @param request         the request
 * @param service         the service
 * @param serviceTicketId the service ticket id
 * @return the model and view
 */
protected ModelAndView handleTicketValidation(final HttpServletRequest request, final WebApplicationService service, final String serviceTicketId) {
    TicketGrantingTicket proxyGrantingTicketId = null;
    final Credential serviceCredential = getServiceCredentialsFromRequest(service, request);
    if (serviceCredential != null) {
        try {
            proxyGrantingTicketId = handleProxyGrantingTicketDelivery(serviceTicketId, serviceCredential);
        } catch (final AuthenticationException e) {
            LOGGER.warn("Failed to authenticate service credential [{}]", serviceCredential);
            return generateErrorView(CasProtocolConstants.ERROR_CODE_INVALID_PROXY_CALLBACK, new Object[] { serviceCredential.getId() }, request, service);
        } catch (final InvalidTicketException e) {
            LOGGER.error("Failed to create proxy granting ticket due to an invalid ticket for [{}]", serviceCredential, e);
            return generateErrorView(e.getCode(), new Object[] { serviceTicketId }, request, service);
        } catch (final AbstractTicketException e) {
            LOGGER.error("Failed to create proxy granting ticket for [{}]", serviceCredential, e);
            return generateErrorView(e.getCode(), new Object[] { serviceCredential.getId() }, request, service);
        }
    }
    final Assertion assertion = this.centralAuthenticationService.validateServiceTicket(serviceTicketId, service);
    if (!validateAssertion(request, serviceTicketId, assertion, service)) {
        return generateErrorView(CasProtocolConstants.ERROR_CODE_INVALID_TICKET, new Object[] { serviceTicketId }, request, service);
    }
    final Pair<Boolean, Optional<MultifactorAuthenticationProvider>> ctxResult = validateAuthenticationContext(assertion, request);
    if (!ctxResult.getKey()) {
        throw new UnsatisfiedAuthenticationContextTicketValidationException(assertion.getService());
    }
    String proxyIou = null;
    if (serviceCredential != null && this.proxyHandler != null && this.proxyHandler.canHandle(serviceCredential)) {
        proxyIou = handleProxyIouDelivery(serviceCredential, proxyGrantingTicketId);
        if (StringUtils.isEmpty(proxyIou)) {
            return generateErrorView(CasProtocolConstants.ERROR_CODE_INVALID_PROXY_CALLBACK, new Object[] { serviceCredential.getId() }, request, service);
        }
    } else {
        LOGGER.debug("No service credentials specified, and/or the proxy handler [{}] cannot handle credentials", this.proxyHandler);
    }
    onSuccessfulValidation(serviceTicketId, assertion);
    LOGGER.debug("Successfully validated service ticket [{}] for service [{}]", serviceTicketId, service.getId());
    return generateSuccessView(assertion, proxyIou, service, request, ctxResult.getValue(), proxyGrantingTicketId);
}
Also used : Credential(org.apereo.cas.authentication.Credential) HttpBasedServiceCredential(org.apereo.cas.authentication.HttpBasedServiceCredential) Optional(java.util.Optional) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) Assertion(org.apereo.cas.validation.Assertion) AbstractTicketException(org.apereo.cas.ticket.AbstractTicketException) UnsatisfiedAuthenticationContextTicketValidationException(org.apereo.cas.ticket.UnsatisfiedAuthenticationContextTicketValidationException)

Example 7 with AbstractTicketException

use of org.apereo.cas.ticket.AbstractTicketException in project cas by apereo.

the class AbstractServiceValidateController method handleRequestInternal.

@Override
public ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final WebApplicationService service = this.argumentExtractor.extractService(request);
    final String serviceTicketId = service != null ? service.getArtifactId() : null;
    if (service == null || !StringUtils.hasText(serviceTicketId)) {
        LOGGER.debug("Could not identify service and/or service ticket for service: [{}]", service);
        return generateErrorView(CasProtocolConstants.ERROR_CODE_INVALID_REQUEST, null, request, service);
    }
    try {
        prepareForTicketValidation(request, service, serviceTicketId);
        return handleTicketValidation(request, service, serviceTicketId);
    } catch (final AbstractTicketValidationException e) {
        final String code = e.getCode();
        return generateErrorView(code, new Object[] { serviceTicketId, e.getService().getId(), service.getId() }, request, service);
    } catch (final AbstractTicketException e) {
        return generateErrorView(e.getCode(), new Object[] { serviceTicketId }, request, service);
    } catch (final UnauthorizedProxyingException e) {
        return generateErrorView(CasProtocolConstants.ERROR_CODE_UNAUTHORIZED_SERVICE_PROXY, new Object[] { service.getId() }, request, service);
    } catch (final UnauthorizedServiceException | PrincipalException e) {
        return generateErrorView(CasProtocolConstants.ERROR_CODE_UNAUTHORIZED_SERVICE, null, request, service);
    }
}
Also used : WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) AbstractTicketValidationException(org.apereo.cas.ticket.AbstractTicketValidationException) PrincipalException(org.apereo.cas.authentication.PrincipalException) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) AbstractTicketException(org.apereo.cas.ticket.AbstractTicketException) UnauthorizedProxyingException(org.apereo.cas.services.UnauthorizedProxyingException)

Example 8 with AbstractTicketException

use of org.apereo.cas.ticket.AbstractTicketException in project cas by apereo.

the class OpenIdServiceResponseBuilder method build.

/**
     * Generates an Openid response.
     * If no ticketId is found, response is negative.
     * If we have a ticket id, then we check if we have an association.
     * If so, we ask OpenId server manager to generate the answer according with the existing association.
     * If not, we send back an answer with the ticket id as association handle.
     * This will force the consumer to ask a verification, which will validate the service ticket.
     *
     * @param ticketId              the service ticket to provide to the service.
     * @param webApplicationService the service requesting an openid response
     * @return the generated authentication answer
     */
@Override
public Response build(final WebApplicationService webApplicationService, final String ticketId) {
    final OpenIdService service = (OpenIdService) webApplicationService;
    final ParameterList parameterList = new ParameterList(WebUtils.getHttpServletRequestFromRequestAttributes().getParameterMap());
    final Map<String, String> parameters = new HashMap<>();
    if (StringUtils.isBlank(ticketId)) {
        parameters.put(OpenIdProtocolConstants.OPENID_MODE, OpenIdProtocolConstants.CANCEL);
        return buildRedirect(service, parameters);
    }
    final Association association = getAssociation(serverManager, parameterList);
    final boolean associated = association != null;
    final boolean associationValid = isAssociationValid(association);
    boolean successFullAuthentication = true;
    Assertion assertion = null;
    try {
        if (associated && associationValid) {
            assertion = centralAuthenticationService.validateServiceTicket(ticketId, service);
            LOGGER.debug("Validated openid ticket [{}] for [{}]", ticketId, service);
        } else if (!associated) {
            LOGGER.debug("Responding to non-associated mode. Service ticket [{}] must be validated by the RP", ticketId);
        } else {
            LOGGER.warn("Association does not exist or is not valid");
            successFullAuthentication = false;
        }
    } catch (final AbstractTicketException e) {
        LOGGER.error("Could not validate ticket : [{}]", e.getMessage(), e);
        successFullAuthentication = false;
    }
    final String id = determineIdentity(service, assertion);
    return buildAuthenticationResponse(service, parameters, successFullAuthentication, id, parameterList);
}
Also used : Association(org.openid4java.association.Association) HashMap(java.util.HashMap) Assertion(org.apereo.cas.validation.Assertion) ParameterList(org.openid4java.message.ParameterList) AbstractTicketException(org.apereo.cas.ticket.AbstractTicketException)

Example 9 with AbstractTicketException

use of org.apereo.cas.ticket.AbstractTicketException in project cas by apereo.

the class WsFederationAction method doExecute.

/**
     * Executes the webflow action.
     *
     * @param context the context
     * @return the event
     * @throws Exception all unhandled exceptions
     */
@Override
protected Event doExecute(final RequestContext context) throws Exception {
    try {
        final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
        final HttpSession session = request.getSession();
        final String wa = request.getParameter(WA);
        // it's an authentication
        if (StringUtils.isNotBlank(wa) && wa.equalsIgnoreCase(WSIGNIN)) {
            final String wResult = request.getParameter(WRESULT);
            LOGGER.debug("Parameter [{}] received: [{}]", WRESULT, wResult);
            if (StringUtils.isBlank(wResult)) {
                LOGGER.error("No [{}] parameter is found", WRESULT);
                return error();
            }
            // create credentials
            LOGGER.debug("Attempting to create an assertion from the token parameter");
            final Assertion assertion = this.wsFederationHelper.parseTokenFromString(wResult, configuration);
            if (assertion == null) {
                LOGGER.error("Could not validate assertion via parsing the token from [{}]", WRESULT);
                return error();
            }
            LOGGER.debug("Attempting to validate the signature on the assertion");
            if (!this.wsFederationHelper.validateSignature(assertion, this.configuration)) {
                LOGGER.error("WS Requested Security Token is blank or the signature is not valid.");
                return error();
            }
            try {
                final Service service = (Service) session.getAttribute(SERVICE);
                LOGGER.debug("Creating credential based on the provided assertion");
                final WsFederationCredential credential = this.wsFederationHelper.createCredentialFromToken(assertion);
                final String rpId = getRelyingPartyIdentifier(service);
                if (credential != null && credential.isValid(rpId, this.configuration.getIdentityProviderIdentifier(), this.configuration.getTolerance())) {
                    LOGGER.debug("Validated assertion for the created credential successfully");
                    if (this.configuration.getAttributeMutator() != null) {
                        LOGGER.debug("Modifying credential attributes based on [{}]", this.configuration.getAttributeMutator().getClass().getSimpleName());
                        this.configuration.getAttributeMutator().modifyAttributes(credential.getAttributes());
                    }
                } else {
                    LOGGER.warn("SAML assertions are blank or no longer valid based on RP identifier [{}] and IdP identifier [{}]", rpId, this.configuration.getIdentityProviderIdentifier());
                    final String url = authorizationUrl + rpId;
                    context.getFlowScope().put(PROVIDERURL, url);
                    LOGGER.warn("Created authentication url [{}] and returning error", url);
                    return error();
                }
                context.getFlowScope().put(SERVICE, service);
                restoreRequestAttribute(request, session, THEME);
                restoreRequestAttribute(request, session, LOCALE);
                restoreRequestAttribute(request, session, METHOD);
                LOGGER.debug("Creating final authentication result based on the given credential");
                final AuthenticationResult authenticationResult = this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(service, credential);
                LOGGER.debug("Attempting to create a ticket-granting ticket for the authentication result");
                WebUtils.putTicketGrantingTicketInScopes(context, this.centralAuthenticationService.createTicketGrantingTicket(authenticationResult));
                LOGGER.info("Token validated and new [{}] created: [{}]", credential.getClass().getName(), credential);
                return success();
            } catch (final AbstractTicketException e) {
                LOGGER.error(e.getMessage(), e);
                return error();
            }
        } else {
            // no authentication : go to login page. save parameters in web session
            final Service service = (Service) context.getFlowScope().get(SERVICE);
            if (service != null) {
                session.setAttribute(SERVICE, service);
            }
            saveRequestParameter(request, session, THEME);
            saveRequestParameter(request, session, LOCALE);
            saveRequestParameter(request, session, METHOD);
            final String url = authorizationUrl + getRelyingPartyIdentifier(service);
            LOGGER.info("Preparing to redirect to the IdP [{}]", url);
            context.getFlowScope().put(PROVIDERURL, url);
        }
        LOGGER.debug("Returning error event");
        return error();
    } catch (final Exception ex) {
        LOGGER.error(ex.getMessage(), ex);
        return error();
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpSession(javax.servlet.http.HttpSession) Assertion(org.opensaml.saml.saml1.core.Assertion) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) AbstractTicketException(org.apereo.cas.ticket.AbstractTicketException) AbstractTicketException(org.apereo.cas.ticket.AbstractTicketException) WsFederationCredential(org.apereo.cas.support.wsfederation.authentication.principal.WsFederationCredential) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult)

Example 10 with AbstractTicketException

use of org.apereo.cas.ticket.AbstractTicketException in project cas by apereo.

the class GenerateServiceTicketAction method doExecute.

/**
 * {@inheritDoc}
 * <p>
 * In the initial primary authentication flow, credentials are cached and available.
 * Since they are authenticated as part of submission first, there is no need to doubly
 * authenticate and verify credentials.
 * <p>
 * In subsequent authentication flows where a TGT is available and only an ST needs to be
 * created, there are no cached copies of the credential, since we do have a TGT available.
 * So we will simply grab the available authentication and produce the final result based on that.
 */
@Override
protected Event doExecute(final RequestContext context) {
    final Service service = WebUtils.getService(context);
    LOGGER.debug("Service asking for service ticket is [{}]", service);
    final String ticketGrantingTicket = WebUtils.getTicketGrantingTicketId(context);
    LOGGER.debug("Ticket-granting ticket found in the context is [{}]", ticketGrantingTicket);
    try {
        final Authentication authentication = this.ticketRegistrySupport.getAuthenticationFrom(ticketGrantingTicket);
        if (authentication == null) {
            throw new InvalidTicketException(new AuthenticationException("No authentication found for ticket " + ticketGrantingTicket), ticketGrantingTicket);
        }
        final Service selectedService = authenticationRequestServiceSelectionStrategies.resolveService(service);
        final RegisteredService registeredService = servicesManager.findServiceBy(selectedService);
        LOGGER.debug("Registered service asking for service ticket is [{}]", registeredService);
        WebUtils.putRegisteredService(context, registeredService);
        WebUtils.putService(context, service);
        if (registeredService != null) {
            final URI url = registeredService.getAccessStrategy().getUnauthorizedRedirectUrl();
            if (url != null) {
                LOGGER.debug("Registered service may redirect to [{}] for unauthorized access requests", url);
            }
            WebUtils.putUnauthorizedRedirectUrlIntoFlowScope(context, url);
        }
        if (WebUtils.getWarningCookie(context)) {
            LOGGER.debug("Warning cookie is present in the request context. Routing result to [{}] state", CasWebflowConstants.STATE_ID_WARN);
            return result(CasWebflowConstants.STATE_ID_WARN);
        }
        final Credential credential = WebUtils.getCredential(context);
        final AuthenticationResultBuilder builder = this.authenticationSystemSupport.establishAuthenticationContextFromInitial(authentication, credential);
        final AuthenticationResult authenticationResult = builder.build(service);
        LOGGER.debug("Built the final authentication result [{}] to grant service ticket to [{}]", authenticationResult, service);
        final ServiceTicket serviceTicketId = this.centralAuthenticationService.grantServiceTicket(ticketGrantingTicket, service, authenticationResult);
        WebUtils.putServiceTicketInRequestScope(context, serviceTicketId);
        LOGGER.debug("Granted service ticket [{}] and added it to the request scope", serviceTicketId);
        return success();
    } catch (final AbstractTicketException e) {
        if (e instanceof InvalidTicketException) {
            LOGGER.debug("CAS has determined ticket-granting ticket [{}] is invalid and must be destroyed", ticketGrantingTicket);
            this.centralAuthenticationService.destroyTicketGrantingTicket(ticketGrantingTicket);
        }
        if (isGatewayPresent(context)) {
            LOGGER.debug("Request indicates that it is gateway. Routing result to [{}] state", CasWebflowConstants.STATE_ID_GATEWAY);
            return result(CasWebflowConstants.STATE_ID_GATEWAY);
        }
        LOGGER.warn("Could not grant service ticket [{}]. Routing to [{}]", e.getMessage(), CasWebflowConstants.TRANSITION_ID_AUTHENTICATION_FAILURE);
        return newEvent(CasWebflowConstants.TRANSITION_ID_AUTHENTICATION_FAILURE, e);
    }
}
Also used : Credential(org.apereo.cas.authentication.Credential) RegisteredService(org.apereo.cas.services.RegisteredService) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) Authentication(org.apereo.cas.authentication.Authentication) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) ServiceTicket(org.apereo.cas.ticket.ServiceTicket) AbstractTicketException(org.apereo.cas.ticket.AbstractTicketException) AuthenticationResultBuilder(org.apereo.cas.authentication.AuthenticationResultBuilder) URI(java.net.URI) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult)

Aggregations

AbstractTicketException (org.apereo.cas.ticket.AbstractTicketException)13 AuthenticationException (org.apereo.cas.authentication.AuthenticationException)5 CentralAuthenticationService (org.apereo.cas.CentralAuthenticationService)4 AuthenticationResult (org.apereo.cas.authentication.AuthenticationResult)4 Service (org.apereo.cas.authentication.principal.Service)4 Credential (org.apereo.cas.authentication.Credential)3 RegisteredService (org.apereo.cas.services.RegisteredService)3 Assertion (org.apereo.cas.validation.Assertion)3 HashMap (java.util.HashMap)2 Authentication (org.apereo.cas.authentication.Authentication)2 UnauthorizedServiceException (org.apereo.cas.services.UnauthorizedServiceException)2 InvalidTicketException (org.apereo.cas.ticket.InvalidTicketException)2 ServiceTicket (org.apereo.cas.ticket.ServiceTicket)2 Ticket (org.apereo.cas.ticket.Ticket)2 Association (org.openid4java.association.Association)2 ParameterList (org.openid4java.message.ParameterList)2 Event (org.springframework.webflow.execution.Event)2 URI (java.net.URI)1 Map (java.util.Map)1 Optional (java.util.Optional)1