Search in sources :

Example 6 with RegisteredService

use of org.apereo.cas.services.RegisteredService 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 7 with RegisteredService

use of org.apereo.cas.services.RegisteredService in project cas by apereo.

the class AdaptiveMultifactorAuthenticationPolicyEventResolver method resolveInternal.

@Override
public Set<Event> resolveInternal(final RequestContext context) {
    final RegisteredService service = resolveRegisteredServiceInRequestContext(context);
    final Authentication authentication = WebUtils.getAuthentication(context);
    if (service == null || authentication == null) {
        LOGGER.debug("No service or authentication is available to determine event for principal");
        return null;
    }
    if (multifactorMap == null || multifactorMap.isEmpty()) {
        LOGGER.debug("Adaptive authentication is not configured to require multifactor authentication");
        return null;
    }
    final Map<String, MultifactorAuthenticationProvider> providerMap = WebUtils.getAvailableMultifactorAuthenticationProviders(this.applicationContext);
    if (providerMap == null || providerMap.isEmpty()) {
        LOGGER.error("No multifactor authentication providers are available in the application context");
        throw new AuthenticationException();
    }
    final Set<Event> providerFound = checkRequireMultifactorProvidersForRequest(context, service, authentication);
    if (providerFound != null && !providerFound.isEmpty()) {
        LOGGER.warn("Found multifactor authentication providers [{}] required for this authentication event", providerFound);
        return providerFound;
    }
    return null;
}
Also used : RegisteredService(org.apereo.cas.services.RegisteredService) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) Authentication(org.apereo.cas.authentication.Authentication) Event(org.springframework.webflow.execution.Event) MultifactorAuthenticationProvider(org.apereo.cas.services.MultifactorAuthenticationProvider)

Example 8 with RegisteredService

use of org.apereo.cas.services.RegisteredService in project cas by apereo.

the class RegisteredServicePrincipalAttributeMultifactorAuthenticationPolicyEventResolver method resolveInternal.

@Override
public Set<Event> resolveInternal(final RequestContext context) {
    final RegisteredService service = resolveRegisteredServiceInRequestContext(context);
    final Authentication authentication = WebUtils.getAuthentication(context);
    final RegisteredServiceMultifactorPolicy policy = service != null ? service.getMultifactorPolicy() : null;
    if (policy == null || service.getMultifactorPolicy().getMultifactorAuthenticationProviders().isEmpty()) {
        LOGGER.debug("Authentication policy is absent or does not contain any multifactor authentication providers");
        return null;
    }
    if (StringUtils.isBlank(policy.getPrincipalAttributeNameTrigger()) || StringUtils.isBlank(policy.getPrincipalAttributeValueToMatch())) {
        LOGGER.debug("Authentication policy does not define a principal attribute and/or value to trigger multifactor authentication");
        return null;
    }
    final Principal principal = authentication.getPrincipal();
    final Collection<MultifactorAuthenticationProvider> providers = flattenProviders(getAuthenticationProviderForService(service));
    return resolveEventViaPrincipalAttribute(principal, org.springframework.util.StringUtils.commaDelimitedListToSet(policy.getPrincipalAttributeNameTrigger()), service, context, providers, Pattern.compile(policy.getPrincipalAttributeValueToMatch()).asPredicate());
}
Also used : RegisteredServiceMultifactorPolicy(org.apereo.cas.services.RegisteredServiceMultifactorPolicy) RegisteredService(org.apereo.cas.services.RegisteredService) Authentication(org.apereo.cas.authentication.Authentication) MultifactorAuthenticationProvider(org.apereo.cas.services.MultifactorAuthenticationProvider) Principal(org.apereo.cas.authentication.principal.Principal)

Example 9 with RegisteredService

use of org.apereo.cas.services.RegisteredService in project cas by apereo.

the class RequestParameterMultifactorAuthenticationPolicyEventResolver method resolveInternal.

@Override
public Set<Event> resolveInternal(final RequestContext context) {
    final RegisteredService service = resolveRegisteredServiceInRequestContext(context);
    final Authentication authentication = WebUtils.getAuthentication(context);
    if (service == null || authentication == null) {
        LOGGER.debug("No service or authentication is available to determine event for principal");
        return null;
    }
    if (StringUtils.isBlank(mfaRequestParameter)) {
        LOGGER.debug("No request parameter is defined to trigger multifactor authentication.");
        return null;
    }
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final String[] values = request.getParameterValues(mfaRequestParameter);
    if (values != null && values.length > 0) {
        LOGGER.debug("Received request parameter [{}] as [{}]", mfaRequestParameter, values);
        final Map<String, MultifactorAuthenticationProvider> providerMap = WebUtils.getAvailableMultifactorAuthenticationProviders(this.applicationContext);
        if (providerMap == null || providerMap.isEmpty()) {
            LOGGER.error("No multifactor authentication providers are available in the application context to satisfy [{}]", (Object[]) values);
            throw new AuthenticationException();
        }
        final Optional<MultifactorAuthenticationProvider> providerFound = resolveProvider(providerMap, values[0]);
        if (providerFound.isPresent()) {
            final MultifactorAuthenticationProvider provider = providerFound.get();
            if (provider.isAvailable(service)) {
                LOGGER.debug("Attempting to build an event based on the authentication provider [{}] and service [{}]", provider, service.getName());
                final Event event = validateEventIdForMatchingTransitionInContext(provider.getId(), context, buildEventAttributeMap(authentication.getPrincipal(), service, provider));
                return Collections.singleton(event);
            }
            LOGGER.warn("Located multifactor provider [{}], yet the provider cannot be reached or verified", providerFound.get());
            return null;
        } else {
            LOGGER.warn("No multifactor provider could be found for request parameter [{}]", (Object[]) values);
            throw new AuthenticationException();
        }
    }
    LOGGER.debug("No value could be found for request parameter [{}]", mfaRequestParameter);
    return null;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) RegisteredService(org.apereo.cas.services.RegisteredService) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) Authentication(org.apereo.cas.authentication.Authentication) Event(org.springframework.webflow.execution.Event) MultifactorAuthenticationProvider(org.apereo.cas.services.MultifactorAuthenticationProvider)

Example 10 with RegisteredService

use of org.apereo.cas.services.RegisteredService in project cas by apereo.

the class InitialFlowSetupAction method configureWebflowContextForService.

private void configureWebflowContextForService(final RequestContext context) {
    final Service service = WebUtils.getService(this.argumentExtractors, context);
    if (service != null) {
        LOGGER.debug("Placing service in context scope: [{}]", service.getId());
        final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
        if (registeredService != null && registeredService.getAccessStrategy().isServiceAccessAllowed()) {
            LOGGER.debug("Placing registered service [{}] with id [{}] in context scope", registeredService.getServiceId(), registeredService.getId());
            WebUtils.putRegisteredService(context, registeredService);
            final RegisteredServiceAccessStrategy accessStrategy = registeredService.getAccessStrategy();
            if (accessStrategy.getUnauthorizedRedirectUrl() != null) {
                LOGGER.debug("Placing registered service's unauthorized redirect url [{}] with id [{}] in context scope", accessStrategy.getUnauthorizedRedirectUrl(), registeredService.getServiceId());
                WebUtils.putUnauthorizedRedirectUrl(context, accessStrategy.getUnauthorizedRedirectUrl());
            }
        }
    } else if (!casProperties.getSso().isMissingService()) {
        LOGGER.warn("No service authentication request is available at [{}]. CAS is configured to disable the flow.", WebUtils.getHttpServletRequest(context).getRequestURL());
        throw new NoSuchFlowExecutionException(context.getFlowExecutionContext().getKey(), new UnauthorizedServiceException("screen.service.required.message", "Service is required"));
    }
    WebUtils.putService(context, service);
}
Also used : RegisteredService(org.apereo.cas.services.RegisteredService) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) RegisteredServiceAccessStrategy(org.apereo.cas.services.RegisteredServiceAccessStrategy) NoSuchFlowExecutionException(org.springframework.webflow.execution.repository.NoSuchFlowExecutionException)

Aggregations

RegisteredService (org.apereo.cas.services.RegisteredService)109 Test (org.junit.Test)39 Authentication (org.apereo.cas.authentication.Authentication)35 Service (org.apereo.cas.authentication.principal.Service)30 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)27 OAuthRegisteredService (org.apereo.cas.support.oauth.services.OAuthRegisteredService)22 Principal (org.apereo.cas.authentication.principal.Principal)21 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)18 RegexRegisteredService (org.apereo.cas.services.RegexRegisteredService)17 AbstractRegisteredService (org.apereo.cas.services.AbstractRegisteredService)13 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)12 Event (org.springframework.webflow.execution.Event)12 ServicesManager (org.apereo.cas.services.ServicesManager)11 HttpServletRequest (javax.servlet.http.HttpServletRequest)10 MultifactorAuthenticationProvider (org.apereo.cas.services.MultifactorAuthenticationProvider)10 OAuthCode (org.apereo.cas.ticket.code.OAuthCode)10 CentralAuthenticationService (org.apereo.cas.CentralAuthenticationService)9 Logger (org.slf4j.Logger)9 LoggerFactory (org.slf4j.LoggerFactory)9 Collection (java.util.Collection)8