Search in sources :

Example 1 with InvalidTicketException

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

the class DefaultCentralAuthenticationService method destroyTicketGrantingTicket.

@Audit(action = "TICKET_GRANTING_TICKET_DESTROYED", actionResolverName = "DESTROY_TICKET_GRANTING_TICKET_RESOLVER", resourceResolverName = "DESTROY_TICKET_GRANTING_TICKET_RESOURCE_RESOLVER")
@Timed(name = "DESTROY_TICKET_GRANTING_TICKET_TIMER")
@Metered(name = "DESTROY_TICKET_GRANTING_TICKET_METER")
@Counted(name = "DESTROY_TICKET_GRANTING_TICKET_COUNTER", monotonic = true)
@Override
public List<LogoutRequest> destroyTicketGrantingTicket(final String ticketGrantingTicketId) {
    try {
        LOGGER.debug("Removing ticket [{}] from registry...", ticketGrantingTicketId);
        final TicketGrantingTicket ticket = getTicket(ticketGrantingTicketId, TicketGrantingTicket.class);
        LOGGER.debug("Ticket found. Processing logout requests and then deleting the ticket...");
        AuthenticationCredentialsLocalBinder.bindCurrent(ticket.getAuthentication());
        final List<LogoutRequest> logoutRequests = this.logoutManager.performLogout(ticket);
        this.ticketRegistry.deleteTicket(ticketGrantingTicketId);
        doPublishEvent(new CasTicketGrantingTicketDestroyedEvent(this, ticket));
        return logoutRequests;
    } catch (final InvalidTicketException e) {
        LOGGER.debug("TicketGrantingTicket [{}] cannot be found in the ticket registry.", ticketGrantingTicketId);
    }
    return Collections.emptyList();
}
Also used : TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) CasTicketGrantingTicketDestroyedEvent(org.apereo.cas.support.events.ticket.CasTicketGrantingTicketDestroyedEvent) LogoutRequest(org.apereo.cas.logout.LogoutRequest) Audit(org.apereo.inspektr.audit.annotation.Audit) Counted(com.codahale.metrics.annotation.Counted) Metered(com.codahale.metrics.annotation.Metered) Timed(com.codahale.metrics.annotation.Timed)

Example 2 with InvalidTicketException

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

the class DefaultCentralAuthenticationService method validateServiceTicket.

@Audit(action = "SERVICE_TICKET_VALIDATE", actionResolverName = "VALIDATE_SERVICE_TICKET_RESOLVER", resourceResolverName = "VALIDATE_SERVICE_TICKET_RESOURCE_RESOLVER")
@Timed(name = "VALIDATE_SERVICE_TICKET_TIMER")
@Metered(name = "VALIDATE_SERVICE_TICKET_METER")
@Counted(name = "VALIDATE_SERVICE_TICKET_COUNTER", monotonic = true)
@Override
public Assertion validateServiceTicket(final String serviceTicketId, final Service service) throws AbstractTicketException {
    if (!isTicketAuthenticityVerified(serviceTicketId)) {
        LOGGER.info("Service ticket [{}] is not a valid ticket issued by CAS.", serviceTicketId);
        throw new InvalidTicketException(serviceTicketId);
    }
    final ServiceTicket serviceTicket = this.ticketRegistry.getTicket(serviceTicketId, ServiceTicket.class);
    if (serviceTicket == null) {
        LOGGER.info("Service ticket [{}] does not exist.", serviceTicketId);
        throw new InvalidTicketException(serviceTicketId);
    }
    try {
        /*
             * Synchronization on ticket object in case of cache based registry doesn't serialize
             * access to critical section. The reason is that cache pulls serialized data and
             * builds new object, most likely for each pull. Is this synchronization needed here?
             */
        synchronized (serviceTicket) {
            if (serviceTicket.isExpired()) {
                LOGGER.info("ServiceTicket [{}] has expired.", serviceTicketId);
                throw new InvalidTicketException(serviceTicketId);
            }
            if (!serviceTicket.isValidFor(service)) {
                LOGGER.error("Service ticket [{}] with service [{}] does not match supplied service [{}]", serviceTicketId, serviceTicket.getService().getId(), service);
                throw new UnrecognizableServiceForServiceTicketValidationException(serviceTicket.getService());
            }
        }
        final Service selectedService = resolveServiceFromAuthenticationRequest(service);
        LOGGER.debug("Resolved service [{}] from the authentication request", selectedService);
        final RegisteredService registeredService = this.servicesManager.findServiceBy(selectedService);
        LOGGER.debug("Located registered service definition [{}] from [{}] to handle validation request", registeredService, selectedService);
        RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(selectedService, registeredService);
        final TicketGrantingTicket root = serviceTicket.getGrantingTicket().getRoot();
        final Authentication authentication = getAuthenticationSatisfiedByPolicy(root.getAuthentication(), new ServiceContext(selectedService, registeredService));
        final Principal principal = authentication.getPrincipal();
        final RegisteredServiceAttributeReleasePolicy attributePolicy = registeredService.getAttributeReleasePolicy();
        LOGGER.debug("Attribute policy [{}] is associated with service [{}]", attributePolicy, registeredService);
        @SuppressWarnings("unchecked") final Map<String, Object> attributesToRelease = attributePolicy != null ? attributePolicy.getAttributes(principal, registeredService) : new HashMap<>();
        final String principalId = registeredService.getUsernameAttributeProvider().resolveUsername(principal, selectedService);
        final Principal modifiedPrincipal = this.principalFactory.createPrincipal(principalId, attributesToRelease);
        final AuthenticationBuilder builder = DefaultAuthenticationBuilder.newInstance(authentication);
        builder.setPrincipal(modifiedPrincipal);
        final Authentication finalAuthentication = builder.build();
        AuthenticationCredentialsLocalBinder.bindCurrent(finalAuthentication);
        final Assertion assertion = new ImmutableAssertion(finalAuthentication, serviceTicket.getGrantingTicket().getChainedAuthentications(), selectedService, serviceTicket.isFromNewLogin());
        doPublishEvent(new CasServiceTicketValidatedEvent(this, serviceTicket, assertion));
        return assertion;
    } finally {
        if (serviceTicket.isExpired()) {
            this.ticketRegistry.deleteTicket(serviceTicketId);
        } else {
            this.ticketRegistry.updateTicket(serviceTicket);
        }
    }
}
Also used : RegisteredService(org.apereo.cas.services.RegisteredService) DefaultAuthenticationBuilder(org.apereo.cas.authentication.DefaultAuthenticationBuilder) AuthenticationBuilder(org.apereo.cas.authentication.AuthenticationBuilder) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) ServiceContext(org.apereo.cas.services.ServiceContext) UnrecognizableServiceForServiceTicketValidationException(org.apereo.cas.ticket.UnrecognizableServiceForServiceTicketValidationException) Assertion(org.apereo.cas.validation.Assertion) ImmutableAssertion(org.apereo.cas.validation.ImmutableAssertion) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) ServiceTicket(org.apereo.cas.ticket.ServiceTicket) ImmutableAssertion(org.apereo.cas.validation.ImmutableAssertion) Authentication(org.apereo.cas.authentication.Authentication) CasServiceTicketValidatedEvent(org.apereo.cas.support.events.ticket.CasServiceTicketValidatedEvent) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) Principal(org.apereo.cas.authentication.principal.Principal) RegisteredServiceAttributeReleasePolicy(org.apereo.cas.services.RegisteredServiceAttributeReleasePolicy) Audit(org.apereo.inspektr.audit.annotation.Audit) Counted(com.codahale.metrics.annotation.Counted) Metered(com.codahale.metrics.annotation.Metered) Timed(com.codahale.metrics.annotation.Timed)

Example 3 with InvalidTicketException

use of org.apereo.cas.ticket.InvalidTicketException 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 4 with InvalidTicketException

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

the class GenericSuccessViewActionTests method verifyPrincipalCanNotBeDetermined.

@Test
public void verifyPrincipalCanNotBeDetermined() throws InvalidTicketException {
    final CentralAuthenticationService cas = mock(CentralAuthenticationService.class);
    final ServicesManager mgr = mock(ServicesManager.class);
    final ServiceFactory factory = mock(ServiceFactory.class);
    when(cas.getTicket(any(String.class), any(Ticket.class.getClass()))).thenThrow(new InvalidTicketException("TGT-1"));
    final GenericSuccessViewAction action = new GenericSuccessViewAction(cas, mgr, factory, "");
    final Principal p = action.getAuthenticationPrincipal("TGT-1");
    assertNotNull(p);
    assertTrue(p instanceof NullPrincipal);
}
Also used : NullPrincipal(org.apereo.cas.authentication.principal.NullPrincipal) ServicesManager(org.apereo.cas.services.ServicesManager) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) ServiceFactory(org.apereo.cas.authentication.principal.ServiceFactory) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) NullPrincipal(org.apereo.cas.authentication.principal.NullPrincipal) Principal(org.apereo.cas.authentication.principal.Principal) Test(org.junit.Test)

Example 5 with InvalidTicketException

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

the class RegisteredServiceResource method createService.

/**
     * Create new service.
     *
     * @param tgtId             ticket granting ticket id URI path param
     * @param serviceDataHolder the service to register and save in rest form
     * @return {@link ResponseEntity} representing RESTful response
     */
@PostMapping(value = "/v1/services/add/{tgtId:.+}", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<String> createService(@ModelAttribute final ServiceDataHolder serviceDataHolder, @PathVariable("tgtId") final String tgtId) {
    try {
        if (StringUtils.isBlank(this.attributeName) || StringUtils.isBlank(this.attributeValue)) {
            throw new IllegalArgumentException("Attribute name and/or value must be configured");
        }
        final TicketGrantingTicket ticket = this.centralAuthenticationService.getTicket(tgtId, TicketGrantingTicket.class);
        if (ticket == null || ticket.isExpired()) {
            throw new InvalidTicketException("Ticket-granting ticket " + tgtId + " is not found");
        }
        final Map<String, Object> attributes = ticket.getAuthentication().getPrincipal().getAttributes();
        if (attributes.containsKey(this.attributeName)) {
            final Collection<String> attributeValuesToCompare = new HashSet<>();
            final Object value = attributes.get(this.attributeName);
            if (value instanceof Collection) {
                attributeValuesToCompare.addAll((Collection<String>) value);
            } else {
                attributeValuesToCompare.add(value.toString());
            }
            if (attributeValuesToCompare.contains(this.attributeValue)) {
                final RegisteredService service = serviceDataHolder.getRegisteredService();
                final RegisteredService savedService = this.servicesManager.save(service);
                return new ResponseEntity<>(String.valueOf(savedService.getId()), HttpStatus.OK);
            }
        }
        throw new IllegalArgumentException("Request is not authorized");
    } 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.BAD_REQUEST);
    }
}
Also used : RegexRegisteredService(org.apereo.cas.services.RegexRegisteredService) RegisteredService(org.apereo.cas.services.RegisteredService) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) ResponseEntity(org.springframework.http.ResponseEntity) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) Collection(java.util.Collection) HashSet(java.util.HashSet) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Aggregations

InvalidTicketException (org.apereo.cas.ticket.InvalidTicketException)12 ServiceTicket (org.apereo.cas.ticket.ServiceTicket)6 Authentication (org.apereo.cas.authentication.Authentication)5 TicketGrantingTicket (org.apereo.cas.ticket.TicketGrantingTicket)5 CentralAuthenticationService (org.apereo.cas.CentralAuthenticationService)4 AuthenticationException (org.apereo.cas.authentication.AuthenticationException)4 Credential (org.apereo.cas.authentication.Credential)4 Service (org.apereo.cas.authentication.principal.Service)4 RegisteredService (org.apereo.cas.services.RegisteredService)4 Counted (com.codahale.metrics.annotation.Counted)3 Metered (com.codahale.metrics.annotation.Metered)3 Timed (com.codahale.metrics.annotation.Timed)3 AuthenticationResult (org.apereo.cas.authentication.AuthenticationResult)3 AuthenticationResultBuilder (org.apereo.cas.authentication.AuthenticationResultBuilder)3 Audit (org.apereo.inspektr.audit.annotation.Audit)3 Test (org.junit.Test)3 Principal (org.apereo.cas.authentication.principal.Principal)2 AbstractTicketException (org.apereo.cas.ticket.AbstractTicketException)2 Assertion (org.apereo.cas.validation.Assertion)2 ResponseEntity (org.springframework.http.ResponseEntity)2