Search in sources :

Example 1 with Assertion

use of org.apereo.cas.validation.Assertion in project cas by apereo.

the class CentralAuthenticationServiceImplTests method authenticateTwiceWithRenew.

/**
     * This test simulates :
     * - a first authentication for a default service
     * - a second authentication with the renew parameter and the same service (and same credentials)
     * - a validation of the second ticket.
     * When supplemental authentications were returned with the chained authentications, the validation specification
     * failed as it only expects one authentication. Thus supplemental authentications should not be returned in the
     * chained authentications. Both concepts are orthogonal.
     */
@Test
public void authenticateTwiceWithRenew() throws AbstractTicketException, AuthenticationException {
    final CentralAuthenticationService cas = getCentralAuthenticationService();
    final Service svc = getService("testDefault");
    final UsernamePasswordCredential goodCredential = CoreAuthenticationTestUtils.getCredentialsWithSameUsernameAndPassword();
    final AuthenticationResult ctx = CoreAuthenticationTestUtils.getAuthenticationResult(getAuthenticationSystemSupport(), svc);
    final TicketGrantingTicket tgtId = cas.createTicketGrantingTicket(ctx);
    cas.grantServiceTicket(tgtId.getId(), svc, ctx);
    // simulate renew with new good same credentials
    final ServiceTicket st2Id = cas.grantServiceTicket(tgtId.getId(), svc, ctx);
    final Assertion assertion = cas.validateServiceTicket(st2Id.getId(), svc);
    final ValidationSpecification validationSpecification = new Cas20WithoutProxyingValidationSpecification();
    assertTrue(validationSpecification.isSatisfiedBy(assertion, new MockHttpServletRequest()));
}
Also used : Cas20WithoutProxyingValidationSpecification(org.apereo.cas.validation.Cas20WithoutProxyingValidationSpecification) ValidationSpecification(org.apereo.cas.validation.ValidationSpecification) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Assertion(org.apereo.cas.validation.Assertion) AbstractWebApplicationService(org.apereo.cas.authentication.principal.AbstractWebApplicationService) Service(org.apereo.cas.authentication.principal.Service) ServiceTicket(org.apereo.cas.ticket.ServiceTicket) UsernamePasswordCredential(org.apereo.cas.authentication.UsernamePasswordCredential) Cas20WithoutProxyingValidationSpecification(org.apereo.cas.validation.Cas20WithoutProxyingValidationSpecification) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult) Test(org.junit.Test)

Example 2 with Assertion

use of org.apereo.cas.validation.Assertion in project cas by apereo.

the class PersonDirectoryAttributeResolutionController method releasePrincipalAttributes.

/**
 * Release principal attributes map.
 *
 * @param username the username
 * @param password the password
 * @param service  the service
 * @param request  the request
 * @param response the response
 * @return the map
 * @throws Exception the exception
 */
@PostMapping(value = "/releaseattrs")
@ResponseBody
public Map<String, Object> releasePrincipalAttributes(@RequestParam final String username, @RequestParam final String password, @RequestParam final String service, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    ensureEndpointAccessIsAuthorized(request, response);
    final Map<String, Object> resValidation = new HashMap<>();
    final Service selectedService = this.serviceFactory.createService(service);
    final RegisteredService registeredService = this.servicesManager.findServiceBy(selectedService);
    final UsernamePasswordCredential credential = new UsernamePasswordCredential(username, password);
    final AuthenticationResult result = this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(selectedService, credential);
    final Authentication authentication = result.getAuthentication();
    final Principal principal = authentication.getPrincipal();
    final Map<String, Object> attributesToRelease = registeredService.getAttributeReleasePolicy().getAttributes(principal, selectedService, registeredService);
    final String principalId = registeredService.getUsernameAttributeProvider().resolveUsername(principal, selectedService, registeredService);
    final Principal modifiedPrincipal = this.principalFactory.createPrincipal(principalId, attributesToRelease);
    final AuthenticationBuilder builder = DefaultAuthenticationBuilder.newInstance(authentication);
    builder.setPrincipal(modifiedPrincipal);
    final Authentication finalAuthentication = builder.build();
    final Assertion assertion = new DefaultAssertionBuilder(finalAuthentication).with(selectedService).with(CollectionUtils.wrap(finalAuthentication)).build();
    final Map<String, Object> model = new LinkedHashMap<>();
    model.put(CasViewConstants.MODEL_ATTRIBUTE_NAME_ASSERTION, assertion);
    model.put(CasViewConstants.MODEL_ATTRIBUTE_NAME_SERVICE, selectedService);
    resValidation.put("registeredService", registeredService);
    String copy = renderViewAndGetResult(this.cas1ServiceSuccessView, model, request, response).getKey().getCopy();
    resValidation.put("cas1Response", StringEscapeUtils.escapeXml11(copy));
    if (casProperties.getView().getCas2().isV3ForwardCompatible()) {
        copy = renderViewAndGetResult(this.cas3ServiceSuccessView, model, request, response).getKey().getCopy();
    } else {
        copy = renderViewAndGetResult(this.cas2ServiceSuccessView, model, request, response).getKey().getCopy();
    }
    resValidation.put("cas2Response", StringEscapeUtils.escapeXml11(copy));
    copy = renderViewAndGetResult(this.cas3ServiceSuccessView, model, request, response).getKey().getCopy();
    resValidation.put("cas3XmlResponse", StringEscapeUtils.escapeXml11(copy));
    copy = renderViewAndGetResult(this.cas3ServiceJsonView, model, request, response).getValue().getStringCopy();
    resValidation.put("cas3JsonResponse", copy);
    response.reset();
    return resValidation;
}
Also used : RegisteredService(org.apereo.cas.services.RegisteredService) DefaultAuthenticationBuilder(org.apereo.cas.authentication.DefaultAuthenticationBuilder) AuthenticationBuilder(org.apereo.cas.authentication.AuthenticationBuilder) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Assertion(org.apereo.cas.validation.Assertion) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult) LinkedHashMap(java.util.LinkedHashMap) DefaultAssertionBuilder(org.apereo.cas.validation.DefaultAssertionBuilder) Authentication(org.apereo.cas.authentication.Authentication) UsernamePasswordCredential(org.apereo.cas.authentication.UsernamePasswordCredential) Principal(org.apereo.cas.authentication.principal.Principal) PostMapping(org.springframework.web.bind.annotation.PostMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 3 with Assertion

use of org.apereo.cas.validation.Assertion in project cas by apereo.

the class TicketValidationResourceResolver method resolveFrom.

@Override
public String[] resolveFrom(final JoinPoint joinPoint, final Object object) {
    final List<String> auditResourceResults = new ArrayList<>();
    final String ticketId = AopUtils.unWrapJoinPoint(joinPoint).getArgs()[0].toString();
    auditResourceResults.add(ticketId);
    if (object instanceof Assertion) {
        final Assertion assertion = Assertion.class.cast(object);
        final Authentication authn = assertion.getPrimaryAuthentication();
        try (StringWriter writer = new StringWriter()) {
            final ObjectWriter objectWriter = mapper.writer();
            final Map<String, Object> results = new LinkedHashMap<>();
            results.put("principal", authn.getPrincipal().getId());
            final Map<String, Object> attributes = new LinkedHashMap<>(authn.getAttributes());
            attributes.putAll(authn.getPrincipal().getAttributes());
            results.put("attributes", attributes);
            objectWriter.writeValue(writer, results);
            auditResourceResults.add(writer.toString());
        } catch (final Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
    return auditResourceResults.toArray(new String[] {});
}
Also used : StringWriter(java.io.StringWriter) Authentication(org.apereo.cas.authentication.Authentication) ArrayList(java.util.ArrayList) Assertion(org.apereo.cas.validation.Assertion) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) LinkedHashMap(java.util.LinkedHashMap)

Example 4 with Assertion

use of org.apereo.cas.validation.Assertion 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 5 with Assertion

use of org.apereo.cas.validation.Assertion in project cas by apereo.

the class CentralAuthenticationServiceImplTests method verifyValidateServiceTicketWithInvalidUsernameAttribute.

@Test
public void verifyValidateServiceTicketWithInvalidUsernameAttribute() {
    final Service svc = getService("eduPersonTestInvalid");
    final UsernamePasswordCredential cred = CoreAuthenticationTestUtils.getCredentialsWithSameUsernameAndPassword();
    final AuthenticationResult ctx = CoreAuthenticationTestUtils.getAuthenticationResult(getAuthenticationSystemSupport(), svc);
    final TicketGrantingTicket ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(ctx);
    final ServiceTicket serviceTicket = getCentralAuthenticationService().grantServiceTicket(ticketGrantingTicket.getId(), svc, ctx);
    final Assertion assertion = getCentralAuthenticationService().validateServiceTicket(serviceTicket.getId(), svc);
    final Authentication auth = assertion.getPrimaryAuthentication();
    /*
         * The attribute specified for this service does not resolve.
         * Therefore, we expect the default to be returned.
         */
    assertEquals(auth.getPrincipal().getId(), cred.getUsername());
}
Also used : TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) Authentication(org.apereo.cas.authentication.Authentication) Assertion(org.apereo.cas.validation.Assertion) AbstractWebApplicationService(org.apereo.cas.authentication.principal.AbstractWebApplicationService) Service(org.apereo.cas.authentication.principal.Service) ServiceTicket(org.apereo.cas.ticket.ServiceTicket) UsernamePasswordCredential(org.apereo.cas.authentication.UsernamePasswordCredential) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult) Test(org.junit.Test)

Aggregations

Assertion (org.apereo.cas.validation.Assertion)18 AuthenticationResult (org.apereo.cas.authentication.AuthenticationResult)11 Service (org.apereo.cas.authentication.principal.Service)11 ServiceTicket (org.apereo.cas.ticket.ServiceTicket)11 TicketGrantingTicket (org.apereo.cas.ticket.TicketGrantingTicket)11 Test (org.junit.Test)11 Authentication (org.apereo.cas.authentication.Authentication)9 AbstractWebApplicationService (org.apereo.cas.authentication.principal.AbstractWebApplicationService)9 UsernamePasswordCredential (org.apereo.cas.authentication.UsernamePasswordCredential)6 HashMap (java.util.HashMap)5 LinkedHashMap (java.util.LinkedHashMap)4 lombok.val (lombok.val)3 AbstractTicketException (org.apereo.cas.ticket.AbstractTicketException)3 RegisteredService (org.apereo.cas.services.RegisteredService)2 Cas20WithoutProxyingValidationSpecification (org.apereo.cas.validation.Cas20WithoutProxyingValidationSpecification)2 ParameterList (org.openid4java.message.ParameterList)2 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)2 ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)1 StringWriter (java.io.StringWriter)1 ArrayList (java.util.ArrayList)1