Search in sources :

Example 1 with ServiceContext

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

the class DefaultCentralAuthenticationService method grantServiceTicket.

@Audit(action = "SERVICE_TICKET", actionResolverName = "GRANT_SERVICE_TICKET_RESOLVER", resourceResolverName = "GRANT_SERVICE_TICKET_RESOURCE_RESOLVER")
@Timed(name = "GRANT_SERVICE_TICKET_TIMER")
@Metered(name = "GRANT_SERVICE_TICKET_METER")
@Counted(name = "GRANT_SERVICE_TICKET_COUNTER", monotonic = true)
@Override
public ServiceTicket grantServiceTicket(final String ticketGrantingTicketId, final Service service, final AuthenticationResult authenticationResult) throws AuthenticationException, AbstractTicketException {
    final boolean credentialProvided = authenticationResult != null && authenticationResult.isCredentialProvided();
    final TicketGrantingTicket ticketGrantingTicket = getTicket(ticketGrantingTicketId, TicketGrantingTicket.class);
    final Service selectedService = resolveServiceFromAuthenticationRequest(service);
    final RegisteredService registeredService = this.servicesManager.findServiceBy(selectedService);
    final AuditableContext audit = AuditableContext.builder().service(selectedService).ticketGrantingTicket(ticketGrantingTicket).registeredService(registeredService).retrievePrincipalAttributesFromReleasePolicy(Boolean.FALSE).build();
    final AuditableExecutionResult accessResult = this.registeredServiceAccessStrategyEnforcer.execute(audit);
    accessResult.throwExceptionIfNeeded();
    final Authentication currentAuthentication = evaluatePossibilityOfMixedPrincipals(authenticationResult, ticketGrantingTicket);
    RegisteredServiceAccessStrategyUtils.ensureServiceSsoAccessIsAllowed(registeredService, selectedService, ticketGrantingTicket, credentialProvided);
    evaluateProxiedServiceIfNeeded(selectedService, ticketGrantingTicket, registeredService);
    // Perform security policy check by getting the authentication that satisfies the configured policy
    getAuthenticationSatisfiedByPolicy(currentAuthentication, new ServiceContext(selectedService, registeredService));
    final Authentication latestAuthentication = ticketGrantingTicket.getRoot().getAuthentication();
    AuthenticationCredentialsThreadLocalBinder.bindCurrent(latestAuthentication);
    final Principal principal = latestAuthentication.getPrincipal();
    final ServiceTicketFactory factory = (ServiceTicketFactory) this.ticketFactory.get(ServiceTicket.class);
    final ServiceTicket serviceTicket = factory.create(ticketGrantingTicket, service, credentialProvided, ServiceTicket.class);
    this.ticketRegistry.updateTicket(ticketGrantingTicket);
    this.ticketRegistry.addTicket(serviceTicket);
    LOGGER.info("Granted ticket [{}] for service [{}] and principal [{}]", serviceTicket.getId(), DigestUtils.abbreviate(service.getId()), principal.getId());
    doPublishEvent(new CasServiceTicketGrantedEvent(this, ticketGrantingTicket, serviceTicket));
    return serviceTicket;
}
Also used : AuditableContext(org.apereo.cas.audit.AuditableContext) RegisteredService(org.apereo.cas.services.RegisteredService) ServiceTicketFactory(org.apereo.cas.ticket.ServiceTicketFactory) CasServiceTicketGrantedEvent(org.apereo.cas.support.events.ticket.CasServiceTicketGrantedEvent) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) Authentication(org.apereo.cas.authentication.Authentication) ServiceContext(org.apereo.cas.services.ServiceContext) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) ServiceTicket(org.apereo.cas.ticket.ServiceTicket) AuditableExecutionResult(org.apereo.cas.audit.AuditableExecutionResult) Principal(org.apereo.cas.authentication.principal.Principal) 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 ServiceContext

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

the class RequiredHandlerAuthenticationPolicyFactoryTests method verifyOperation.

@Test
public void verifyOperation() {
    val input = new RequiredHandlerAuthenticationPolicyFactory();
    val policy = input.createPolicy(new ServiceContext(CoreAuthenticationTestUtils.getService(), CoreAuthenticationTestUtils.getRegisteredService()));
    assertNotNull(policy.getContext());
}
Also used : lombok.val(lombok.val) RequiredHandlerAuthenticationPolicyFactory(org.apereo.cas.authentication.policy.RequiredHandlerAuthenticationPolicyFactory) ServiceContext(org.apereo.cas.services.ServiceContext) Test(org.junit.jupiter.api.Test)

Example 3 with ServiceContext

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

the class AcceptAnyAuthenticationPolicyFactoryTests method verifyOperation.

@Test
public void verifyOperation() {
    val input = new AcceptAnyAuthenticationPolicyFactory();
    val policy = input.createPolicy(new ServiceContext(CoreAuthenticationTestUtils.getService(), CoreAuthenticationTestUtils.getRegisteredService()));
    assertNotNull(policy.getContext());
}
Also used : lombok.val(lombok.val) AcceptAnyAuthenticationPolicyFactory(org.apereo.cas.authentication.policy.AcceptAnyAuthenticationPolicyFactory) ServiceContext(org.apereo.cas.services.ServiceContext) Test(org.junit.jupiter.api.Test)

Example 4 with ServiceContext

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

the class DefaultCentralAuthenticationService method grantProxyTicket.

@Audit(action = AuditableActions.PROXY_TICKET, actionResolverName = AuditActionResolvers.GRANT_PROXY_TICKET_RESOLVER, resourceResolverName = AuditResourceResolvers.GRANT_PROXY_TICKET_RESOURCE_RESOLVER)
@Override
public ProxyTicket grantProxyTicket(final String proxyGrantingTicket, final Service service) throws AbstractTicketException {
    val proxyGrantingTicketObject = getTicket(proxyGrantingTicket, ProxyGrantingTicket.class);
    val registeredService = configurationContext.getServicesManager().findServiceBy(service);
    try {
        enforceRegisteredServiceAccess(service, proxyGrantingTicketObject, registeredService);
        RegisteredServiceAccessStrategyUtils.ensureServiceSsoAccessIsAllowed(registeredService, service, proxyGrantingTicketObject);
    } catch (final Exception e) {
        LoggingUtils.warn(LOGGER, e);
        throw new UnauthorizedSsoServiceException();
    }
    evaluateProxiedServiceIfNeeded(service, proxyGrantingTicketObject, registeredService);
    getAuthenticationSatisfiedByPolicy(proxyGrantingTicketObject.getRoot().getAuthentication(), new ServiceContext(service, registeredService));
    val authentication = proxyGrantingTicketObject.getRoot().getAuthentication();
    AuthenticationCredentialsThreadLocalBinder.bindCurrent(authentication);
    return configurationContext.getLockRepository().execute(proxyGrantingTicketObject.getId(), Unchecked.supplier(new CheckedSupplier<ProxyTicket>() {

        @Override
        public ProxyTicket get() throws Throwable {
            val principal = authentication.getPrincipal();
            val factory = (ProxyTicketFactory) configurationContext.getTicketFactory().get(ProxyTicket.class);
            val proxyTicket = factory.create(proxyGrantingTicketObject, service, ProxyTicket.class);
            configurationContext.getTicketRegistry().updateTicket(proxyGrantingTicketObject);
            configurationContext.getTicketRegistry().addTicket(proxyTicket);
            LOGGER.info("Granted proxy ticket [{}] for service [{}] for user [{}]", proxyTicket.getId(), service.getId(), principal.getId());
            doPublishEvent(new CasProxyTicketGrantedEvent(this, proxyGrantingTicketObject, proxyTicket));
            return proxyTicket;
        }
    })).orElseThrow(UnauthorizedProxyingException::new);
}
Also used : lombok.val(lombok.val) UnauthorizedSsoServiceException(org.apereo.cas.services.UnauthorizedSsoServiceException) ServiceContext(org.apereo.cas.services.ServiceContext) UnauthorizedSsoServiceException(org.apereo.cas.services.UnauthorizedSsoServiceException) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) UnauthorizedProxyingException(org.apereo.cas.services.UnauthorizedProxyingException) MixedPrincipalException(org.apereo.cas.authentication.exceptions.MixedPrincipalException) UnrecognizableServiceForServiceTicketValidationException(org.apereo.cas.ticket.UnrecognizableServiceForServiceTicketValidationException) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) AbstractTicketException(org.apereo.cas.ticket.AbstractTicketException) ProxyTicket(org.apereo.cas.ticket.proxy.ProxyTicket) UnauthorizedProxyingException(org.apereo.cas.services.UnauthorizedProxyingException) CasProxyTicketGrantedEvent(org.apereo.cas.support.events.ticket.CasProxyTicketGrantedEvent) Audit(org.apereo.inspektr.audit.annotation.Audit)

Example 5 with ServiceContext

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

the class DefaultCentralAuthenticationService method validateServiceTicket.

@Audit(action = AuditableActions.SERVICE_TICKET_VALIDATE, actionResolverName = AuditActionResolvers.VALIDATE_SERVICE_TICKET_RESOLVER, resourceResolverName = AuditResourceResolvers.VALIDATE_SERVICE_TICKET_RESOURCE_RESOLVER)
@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);
    }
    val serviceTicket = configurationContext.getTicketRegistry().getTicket(serviceTicketId, ServiceTicket.class);
    if (serviceTicket == null) {
        LOGGER.warn("Service ticket [{}] does not exist.", serviceTicketId);
        throw new InvalidTicketException(serviceTicketId);
    }
    try {
        val selectedService = resolveServiceFromAuthenticationRequest(serviceTicket.getService());
        val resolvedService = resolveServiceFromAuthenticationRequest(service);
        LOGGER.debug("Resolved service [{}] from the authentication request with service [{}] linked to service ticket [{}]", resolvedService, selectedService, serviceTicket.getId());
        configurationContext.getLockRepository().execute(serviceTicket.getId(), Unchecked.supplier(() -> {
            if (serviceTicket.isExpired()) {
                LOGGER.info("ServiceTicket [{}] has expired.", serviceTicketId);
                throw new InvalidTicketException(serviceTicketId);
            }
            if (!configurationContext.getServiceMatchingStrategy().matches(selectedService, resolvedService)) {
                LOGGER.error("Service ticket [{}] with service [{}] does not match supplied service [{}]", serviceTicketId, serviceTicket.getService().getId(), resolvedService.getId());
                throw new UnrecognizableServiceForServiceTicketValidationException(selectedService);
            }
            serviceTicket.update();
            configurationContext.getTicketRegistry().updateTicket(serviceTicket);
            return serviceTicket;
        }));
        val registeredService = configurationContext.getServicesManager().findServiceBy(selectedService);
        LOGGER.trace("Located registered service definition [{}] from [{}] to handle validation request", registeredService, selectedService);
        RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(selectedService, registeredService);
        val root = serviceTicket.getTicketGrantingTicket().getRoot();
        val authentication = getAuthenticationSatisfiedByPolicy(root.getAuthentication(), new ServiceContext(selectedService, registeredService));
        val principal = authentication.getPrincipal();
        val attributePolicy = Objects.requireNonNull(registeredService.getAttributeReleasePolicy());
        LOGGER.debug("Attribute policy [{}] is associated with service [{}]", attributePolicy, registeredService);
        val context = RegisteredServiceAttributeReleasePolicyContext.builder().registeredService(registeredService).service(selectedService).principal(principal).build();
        val attributesToRelease = attributePolicy.getAttributes(context);
        LOGGER.debug("Calculated attributes for release per the release policy are [{}]", attributesToRelease.keySet());
        val principalId = registeredService.getUsernameAttributeProvider().resolveUsername(principal, selectedService, registeredService);
        val builder = DefaultAuthenticationBuilder.of(principal, configurationContext.getPrincipalFactory(), attributesToRelease, selectedService, registeredService, authentication);
        LOGGER.debug("Principal determined for release to [{}] is [{}]", registeredService.getServiceId(), principalId);
        builder.addAttribute(CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_FROM_NEW_LOGIN, CollectionUtils.wrap(((RenewableServiceTicket) serviceTicket).isFromNewLogin()));
        builder.addAttribute(CasProtocolConstants.VALIDATION_REMEMBER_ME_ATTRIBUTE_NAME, CollectionUtils.wrap(CoreAuthenticationUtils.isRememberMeAuthentication(authentication)));
        val finalAuthentication = builder.build();
        val releasePolicyContext = RegisteredServiceAttributeReleasePolicyContext.builder().registeredService(registeredService).service(service).principal(principal).build();
        val policyAttributes = registeredService.getAttributeReleasePolicy().getAttributes(releasePolicyContext);
        val merger = CoreAuthenticationUtils.getAttributeMerger(PrincipalAttributesCoreProperties.MergingStrategyTypes.MULTIVALUED);
        var accessAttributes = CoreAuthenticationUtils.mergeAttributes(principal.getAttributes(), authentication.getAttributes(), merger);
        accessAttributes = CoreAuthenticationUtils.mergeAttributes(accessAttributes, finalAuthentication.getPrincipal().getAttributes(), merger);
        accessAttributes = CoreAuthenticationUtils.mergeAttributes(accessAttributes, finalAuthentication.getAttributes(), merger);
        accessAttributes = CoreAuthenticationUtils.mergeAttributes(accessAttributes, policyAttributes, merger);
        val accessPrincipal = configurationContext.getPrincipalFactory().createPrincipal(principal.getId(), accessAttributes);
        enforceRegisteredServiceAccess(selectedService, registeredService, accessPrincipal);
        AuthenticationCredentialsThreadLocalBinder.bindCurrent(finalAuthentication);
        val assertion = new DefaultAssertionBuilder(finalAuthentication).with(selectedService).with(serviceTicket.getTicketGrantingTicket().getChainedAuthentications()).with(((RenewableServiceTicket) serviceTicket).isFromNewLogin()).build();
        doPublishEvent(new CasServiceTicketValidatedEvent(this, serviceTicket, assertion));
        return assertion;
    } finally {
        FunctionUtils.doUnchecked(s -> {
            if (serviceTicket.isExpired()) {
                deleteTicket(serviceTicketId);
            } else {
                configurationContext.getTicketRegistry().updateTicket(serviceTicket);
            }
        });
    }
}
Also used : lombok.val(lombok.val) DefaultAssertionBuilder(org.apereo.cas.validation.DefaultAssertionBuilder) ServiceContext(org.apereo.cas.services.ServiceContext) CasServiceTicketValidatedEvent(org.apereo.cas.support.events.ticket.CasServiceTicketValidatedEvent) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) UnrecognizableServiceForServiceTicketValidationException(org.apereo.cas.ticket.UnrecognizableServiceForServiceTicketValidationException) RenewableServiceTicket(org.apereo.cas.ticket.RenewableServiceTicket) Audit(org.apereo.inspektr.audit.annotation.Audit)

Aggregations

ServiceContext (org.apereo.cas.services.ServiceContext)5 lombok.val (lombok.val)4 Audit (org.apereo.inspektr.audit.annotation.Audit)3 InvalidTicketException (org.apereo.cas.ticket.InvalidTicketException)2 UnrecognizableServiceForServiceTicketValidationException (org.apereo.cas.ticket.UnrecognizableServiceForServiceTicketValidationException)2 Test (org.junit.jupiter.api.Test)2 Counted (com.codahale.metrics.annotation.Counted)1 Metered (com.codahale.metrics.annotation.Metered)1 Timed (com.codahale.metrics.annotation.Timed)1 AuditableContext (org.apereo.cas.audit.AuditableContext)1 AuditableExecutionResult (org.apereo.cas.audit.AuditableExecutionResult)1 Authentication (org.apereo.cas.authentication.Authentication)1 AuthenticationException (org.apereo.cas.authentication.AuthenticationException)1 MixedPrincipalException (org.apereo.cas.authentication.exceptions.MixedPrincipalException)1 AcceptAnyAuthenticationPolicyFactory (org.apereo.cas.authentication.policy.AcceptAnyAuthenticationPolicyFactory)1 RequiredHandlerAuthenticationPolicyFactory (org.apereo.cas.authentication.policy.RequiredHandlerAuthenticationPolicyFactory)1 Principal (org.apereo.cas.authentication.principal.Principal)1 Service (org.apereo.cas.authentication.principal.Service)1 RegisteredService (org.apereo.cas.services.RegisteredService)1 UnauthorizedProxyingException (org.apereo.cas.services.UnauthorizedProxyingException)1