Search in sources :

Example 1 with AuthenticationResultBuilder

use of org.apereo.cas.authentication.AuthenticationResultBuilder in project cas by apereo.

the class ServiceWarningAction method doExecute.

@Override
protected Event doExecute(final RequestContext context) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    final Service service = WebUtils.getService(context);
    final String ticketGrantingTicket = WebUtils.getTicketGrantingTicketId(context);
    final Authentication authentication = this.ticketRegistrySupport.getAuthenticationFrom(ticketGrantingTicket);
    if (authentication == null) {
        throw new InvalidTicketException(new AuthenticationException("No authentication found for ticket " + ticketGrantingTicket), ticketGrantingTicket);
    }
    final Credential credential = WebUtils.getCredential(context);
    final AuthenticationResultBuilder authenticationResultBuilder = authenticationSystemSupport.establishAuthenticationContextFromInitial(authentication, credential);
    final AuthenticationResult authenticationResult = authenticationResultBuilder.build(service);
    final ServiceTicket serviceTicketId = this.centralAuthenticationService.grantServiceTicket(ticketGrantingTicket, service, authenticationResult);
    WebUtils.putServiceTicketInRequestScope(context, serviceTicketId);
    if (request.getParameterMap().containsKey("ignorewarn")) {
        if (Boolean.valueOf(request.getParameter("ignorewarn").toString())) {
            this.warnCookieGenerator.removeCookie(response);
        }
    }
    return new Event(this, CasWebflowConstants.STATE_ID_REDIRECT);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Credential(org.apereo.cas.authentication.Credential) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) Authentication(org.apereo.cas.authentication.Authentication) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) HttpServletResponse(javax.servlet.http.HttpServletResponse) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) Service(org.apereo.cas.authentication.principal.Service) Event(org.springframework.webflow.execution.Event) ServiceTicket(org.apereo.cas.ticket.ServiceTicket) AuthenticationResultBuilder(org.apereo.cas.authentication.AuthenticationResultBuilder) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult)

Example 2 with AuthenticationResultBuilder

use of org.apereo.cas.authentication.AuthenticationResultBuilder in project cas by apereo.

the class TicketsResource method createServiceTicket.

/**
     * Create new service ticket.
     *
     * @param requestBody service application/x-www-form-urlencoded value
     * @param tgtId       ticket granting ticket id URI path param
     * @return {@link ResponseEntity} representing RESTful response
     */
@PostMapping(value = "/v1/tickets/{tgtId:.+}", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<String> createServiceTicket(@RequestBody final MultiValueMap<String, String> requestBody, @PathVariable("tgtId") final String tgtId) {
    try {
        final String serviceId = requestBody.getFirst(CasProtocolConstants.PARAMETER_SERVICE);
        final AuthenticationResultBuilder builder = new DefaultAuthenticationResultBuilder(this.authenticationSystemSupport.getPrincipalElectionStrategy());
        final Service service = this.webApplicationServiceFactory.createService(serviceId);
        final AuthenticationResult authenticationResult = builder.collect(this.ticketRegistrySupport.getAuthenticationFrom(tgtId)).build(service);
        final ServiceTicket serviceTicketId = this.centralAuthenticationService.grantServiceTicket(tgtId, service, authenticationResult);
        return new ResponseEntity<>(serviceTicketId.getId(), HttpStatus.OK);
    } catch (final InvalidTicketException e) {
        return new ResponseEntity<>("TicketGrantingTicket could not be found", HttpStatus.NOT_FOUND);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) Service(org.apereo.cas.authentication.principal.Service) ServiceTicket(org.apereo.cas.ticket.ServiceTicket) DefaultAuthenticationResultBuilder(org.apereo.cas.authentication.DefaultAuthenticationResultBuilder) AuthenticationResultBuilder(org.apereo.cas.authentication.AuthenticationResultBuilder) DefaultAuthenticationResultBuilder(org.apereo.cas.authentication.DefaultAuthenticationResultBuilder) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 3 with AuthenticationResultBuilder

use of org.apereo.cas.authentication.AuthenticationResultBuilder in project cas by apereo.

the class InitialAuthenticationAttemptWebflowEventResolver method resolveInternal.

@Override
public Set<Event> resolveInternal(final RequestContext context) {
    try {
        final Credential credential = getCredentialFromContext(context);
        final Service service = WebUtils.getService(context);
        if (credential != null) {
            final AuthenticationResultBuilder builder = this.authenticationSystemSupport.handleInitialAuthenticationTransaction(service, credential);
            if (builder.getInitialAuthentication().isPresent()) {
                WebUtils.putAuthenticationResultBuilder(builder, context);
                WebUtils.putAuthentication(builder.getInitialAuthentication().get(), context);
            }
        }
        final RegisteredService registeredService = determineRegisteredServiceForEvent(context, service);
        LOGGER.debug("Attempting to resolve candidate authentication events for service [{}]", service);
        final Set<Event> resolvedEvents = resolveCandidateAuthenticationEvents(context, service, registeredService);
        if (!resolvedEvents.isEmpty()) {
            LOGGER.debug("The set of authentication events resolved for [{}] are [{}]. Beginning to select the final event...", service, resolvedEvents);
            putResolvedEventsAsAttribute(context, resolvedEvents);
            final Event finalResolvedEvent = this.selectiveResolver.resolveSingle(context);
            LOGGER.debug("The final authentication event resolved for [{}] is [{}]", service, finalResolvedEvent);
            if (finalResolvedEvent != null) {
                return CollectionUtils.wrapSet(finalResolvedEvent);
            }
        }
        final AuthenticationResultBuilder builder = WebUtils.getAuthenticationResultBuilder(context);
        if (builder == null) {
            throw new IllegalArgumentException("No authentication result builder can be located in the context");
        }
        return CollectionUtils.wrapSet(grantTicketGrantingTicketToAuthenticationResult(context, builder, service));
    } catch (final Exception e) {
        Event event = returnAuthenticationExceptionEventIfNeeded(e);
        if (event == null) {
            LOGGER.warn(e.getMessage(), e);
            event = newEvent(CasWebflowConstants.TRANSITION_ID_ERROR, e);
        }
        final HttpServletResponse response = WebUtils.getHttpServletResponseFromExternalWebflowContext(context);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        return CollectionUtils.wrapSet(event);
    }
}
Also used : Credential(org.apereo.cas.authentication.Credential) RegisteredService(org.apereo.cas.services.RegisteredService) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) Event(org.springframework.webflow.execution.Event) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthenticationResultBuilder(org.apereo.cas.authentication.AuthenticationResultBuilder) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) AbstractTicketException(org.apereo.cas.ticket.AbstractTicketException)

Example 4 with AuthenticationResultBuilder

use of org.apereo.cas.authentication.AuthenticationResultBuilder in project cas by apereo.

the class RankedAuthenticationProviderWebflowEventResolver method resolveInternal.

@Override
public Set<Event> resolveInternal(final RequestContext context) {
    final String tgt = WebUtils.getTicketGrantingTicketId(context);
    final RegisteredService service = WebUtils.getRegisteredService(context);
    if (service == null) {
        LOGGER.debug("No service is available to determine event for principal");
        return resumeFlow();
    }
    if (StringUtils.isBlank(tgt)) {
        LOGGER.trace("TGT is blank; proceed with flow normally.");
        return resumeFlow();
    }
    final Authentication authentication = this.ticketRegistrySupport.getAuthenticationFrom(tgt);
    if (authentication == null) {
        LOGGER.trace("TGT has no authentication and is blank; proceed with flow normally.");
        return resumeFlow();
    }
    final Credential credential = WebUtils.getCredential(context);
    final AuthenticationResultBuilder builder = this.authenticationSystemSupport.establishAuthenticationContextFromInitial(authentication, credential);
    LOGGER.debug("Recording and tracking initial authentication results in the request context");
    WebUtils.putAuthenticationResultBuilder(builder, context);
    WebUtils.putAuthentication(authentication, context);
    final Event event = this.initialAuthenticationAttemptWebflowEventResolver.resolveSingle(context);
    if (event == null) {
        LOGGER.trace("Request does not indicate a requirement for authentication policy; proceed with flow normally.");
        return resumeFlow();
    }
    final String id = event.getId();
    LOGGER.debug("Resolved from the initial authentication leg is [{}]", id);
    if (id.equals(CasWebflowConstants.TRANSITION_ID_ERROR) || id.equals(CasWebflowConstants.TRANSITION_ID_AUTHENTICATION_FAILURE) || id.equals(CasWebflowConstants.TRANSITION_ID_SUCCESS) || id.equals(CasWebflowConstants.TRANSITION_ID_SUCCESS_WITH_WARNINGS)) {
        LOGGER.debug("Returning webflow event as [{}]", id);
        return CollectionUtils.wrapSet(event);
    }
    LOGGER.debug("Validating authentication context for event [{}] and service [{}]", id, service);
    final Pair<Boolean, Optional<MultifactorAuthenticationProvider>> result = this.authenticationContextValidator.validate(authentication, id, service);
    if (result.getKey()) {
        LOGGER.debug("Authentication context is successfully validated by [{}] for service [{}]", id, service);
        return resumeFlow();
    }
    if (result.getValue().isPresent()) {
        return CollectionUtils.wrapSet(validateEventIdForMatchingTransitionInContext(id, context, buildEventAttributeMap(authentication.getPrincipal(), service, result.getValue().get())));
    }
    LOGGER.warn("The authentication context cannot be satisfied and the requested event [{}] is unrecognized", id);
    return CollectionUtils.wrapSet(new Event(this, CasWebflowConstants.TRANSITION_ID_ERROR));
}
Also used : Credential(org.apereo.cas.authentication.Credential) RegisteredService(org.apereo.cas.services.RegisteredService) Optional(java.util.Optional) Authentication(org.apereo.cas.authentication.Authentication) Event(org.springframework.webflow.execution.Event) AuthenticationResultBuilder(org.apereo.cas.authentication.AuthenticationResultBuilder)

Example 5 with AuthenticationResultBuilder

use of org.apereo.cas.authentication.AuthenticationResultBuilder in project cas by apereo.

the class ServiceTicketResource method createServiceTicket.

/**
 * Create new service ticket.
 *
 * @param httpServletRequest http request
 * @param tgtId       ticket granting ticket id URI path param
 * @return {@link ResponseEntity} representing RESTful response
 */
@PostMapping(value = "/v1/tickets/{tgtId:.+}", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<String> createServiceTicket(final HttpServletRequest httpServletRequest, @PathVariable("tgtId") final String tgtId) {
    try {
        final Authentication authn = this.ticketRegistrySupport.getAuthenticationFrom(tgtId);
        AuthenticationCredentialsThreadLocalBinder.bindCurrent(authn);
        if (authn == null) {
            throw new InvalidTicketException(tgtId);
        }
        final AuthenticationResultBuilder builder = new DefaultAuthenticationResultBuilder(this.authenticationSystemSupport.getPrincipalElectionStrategy());
        final Service service = this.argumentExtractor.extractService(httpServletRequest);
        if (service == null) {
            throw new IllegalArgumentException("Target service/application is unspecified or unrecognized in the request");
        }
        final AuthenticationResult authenticationResult = builder.collect(authn).build(service);
        return this.serviceTicketResourceEntityResponseFactory.build(tgtId, service, authenticationResult);
    } catch (final InvalidTicketException e) {
        return new ResponseEntity<>(tgtId + " could not be found or is considered invalid", HttpStatus.NOT_FOUND);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    } finally {
        AuthenticationCredentialsThreadLocalBinder.clear();
    }
}
Also used : Authentication(org.apereo.cas.authentication.Authentication) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) Service(org.apereo.cas.authentication.principal.Service) DefaultAuthenticationResultBuilder(org.apereo.cas.authentication.DefaultAuthenticationResultBuilder) AuthenticationResultBuilder(org.apereo.cas.authentication.AuthenticationResultBuilder) DefaultAuthenticationResultBuilder(org.apereo.cas.authentication.DefaultAuthenticationResultBuilder) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Aggregations

AuthenticationResultBuilder (org.apereo.cas.authentication.AuthenticationResultBuilder)6 Service (org.apereo.cas.authentication.principal.Service)4 CentralAuthenticationService (org.apereo.cas.CentralAuthenticationService)3 Authentication (org.apereo.cas.authentication.Authentication)3 AuthenticationException (org.apereo.cas.authentication.AuthenticationException)3 AuthenticationResult (org.apereo.cas.authentication.AuthenticationResult)3 Credential (org.apereo.cas.authentication.Credential)3 InvalidTicketException (org.apereo.cas.ticket.InvalidTicketException)3 Event (org.springframework.webflow.execution.Event)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 DefaultAuthenticationResultBuilder (org.apereo.cas.authentication.DefaultAuthenticationResultBuilder)2 RegisteredService (org.apereo.cas.services.RegisteredService)2 ServiceTicket (org.apereo.cas.ticket.ServiceTicket)2 PostMapping (org.springframework.web.bind.annotation.PostMapping)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 Optional (java.util.Optional)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 lombok.val (lombok.val)1 AbstractTicketException (org.apereo.cas.ticket.AbstractTicketException)1 ResponseEntity (org.springframework.http.ResponseEntity)1