Search in sources :

Example 1 with DefaultAssertionBuilder

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

the class Saml10SuccessResponseViewTests method verifyResponse.

@Test
public void verifyResponse() throws Exception {
    final Map<String, Object> model = new HashMap<>();
    final Map<String, Object> attributes = new HashMap<>();
    attributes.put(TEST_ATTRIBUTE, TEST_VALUE);
    attributes.put("testEmptyCollection", new ArrayList<>(0));
    attributes.put("testAttributeCollection", Arrays.asList("tac1", "tac2"));
    final Principal principal = new DefaultPrincipalFactory().createPrincipal(PRINCIPAL_ID, attributes);
    final Map<String, Object> authAttributes = new HashMap<>();
    authAttributes.put(SamlAuthenticationMetaDataPopulator.ATTRIBUTE_AUTHENTICATION_METHOD, SamlAuthenticationMetaDataPopulator.AUTHN_METHOD_SSL_TLS_CLIENT);
    authAttributes.put("testSamlAttribute", "value");
    final Authentication primary = CoreAuthenticationTestUtils.getAuthentication(principal, authAttributes);
    final Assertion assertion = new DefaultAssertionBuilder(primary).with(Collections.singletonList(primary)).with(CoreAuthenticationTestUtils.getService()).with(true).build();
    model.put("assertion", assertion);
    final MockHttpServletResponse servletResponse = new MockHttpServletResponse();
    this.response.renderMergedOutputModel(model, new MockHttpServletRequest(), servletResponse);
    final String written = servletResponse.getContentAsString();
    assertTrue(written.contains(PRINCIPAL_ID));
    assertTrue(written.contains(TEST_ATTRIBUTE));
    assertTrue(written.contains(TEST_VALUE));
    assertFalse(written.contains("testEmptyCollection"));
    assertTrue(written.contains("testAttributeCollection"));
    assertTrue(written.contains("tac1"));
    assertTrue(written.contains("tac2"));
    assertTrue(written.contains(SamlAuthenticationMetaDataPopulator.AUTHN_METHOD_SSL_TLS_CLIENT));
    assertTrue(written.contains("AuthenticationMethod"));
    assertTrue(written.contains("AssertionID"));
    assertTrue(written.contains("saml1:Attribute"));
    assertTrue(written.contains("saml1p:Response"));
    assertTrue(written.contains("saml1:Assertion"));
}
Also used : DefaultAssertionBuilder(org.apereo.cas.validation.DefaultAssertionBuilder) HashMap(java.util.HashMap) Authentication(org.apereo.cas.authentication.Authentication) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Assertion(org.apereo.cas.validation.Assertion) DefaultPrincipalFactory(org.apereo.cas.authentication.principal.DefaultPrincipalFactory) Principal(org.apereo.cas.authentication.principal.Principal) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.Test)

Example 2 with DefaultAssertionBuilder

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

the class Saml10SuccessResponseViewTests method verifyResponseWithNoAttributes.

@Test
public void verifyResponseWithNoAttributes() throws Exception {
    final Map<String, Object> model = new HashMap<>();
    final Principal principal = new DefaultPrincipalFactory().createPrincipal(PRINCIPAL_ID);
    final Map<String, Object> authAttributes = new HashMap<>();
    authAttributes.put(SamlAuthenticationMetaDataPopulator.ATTRIBUTE_AUTHENTICATION_METHOD, SamlAuthenticationMetaDataPopulator.AUTHN_METHOD_SSL_TLS_CLIENT);
    authAttributes.put("testSamlAttribute", "value");
    final Authentication primary = CoreAuthenticationTestUtils.getAuthentication(principal, authAttributes);
    final Assertion assertion = new DefaultAssertionBuilder(primary).with(Collections.singletonList(primary)).with(CoreAuthenticationTestUtils.getService()).with(true).build();
    model.put("assertion", assertion);
    final MockHttpServletResponse servletResponse = new MockHttpServletResponse();
    this.response.renderMergedOutputModel(model, new MockHttpServletRequest(), servletResponse);
    final String written = servletResponse.getContentAsString();
    assertTrue(written.contains(PRINCIPAL_ID));
    assertTrue(written.contains(SamlAuthenticationMetaDataPopulator.AUTHN_METHOD_SSL_TLS_CLIENT));
    assertTrue(written.contains("AuthenticationMethod="));
}
Also used : DefaultAssertionBuilder(org.apereo.cas.validation.DefaultAssertionBuilder) HashMap(java.util.HashMap) Authentication(org.apereo.cas.authentication.Authentication) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Assertion(org.apereo.cas.validation.Assertion) DefaultPrincipalFactory(org.apereo.cas.authentication.principal.DefaultPrincipalFactory) Principal(org.apereo.cas.authentication.principal.Principal) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.Test)

Example 3 with DefaultAssertionBuilder

use of org.apereo.cas.validation.DefaultAssertionBuilder 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.warn("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(serviceTicket.getService());
        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.getTicketGrantingTicket().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);
        final Map<String, Object> attributesToRelease = attributePolicy != null ? attributePolicy.getAttributes(principal, selectedService, registeredService) : new HashMap<>();
        LOGGER.debug("Calculated attributes for release per the release policy are [{}]", attributesToRelease.keySet());
        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);
        LOGGER.debug("Principal determined for release to [{}] is [{}]", registeredService.getServiceId(), principalId);
        final Authentication finalAuthentication = builder.build();
        final AuditableContext audit = AuditableContext.builder().service(selectedService).authentication(finalAuthentication).registeredService(registeredService).retrievePrincipalAttributesFromReleasePolicy(Boolean.FALSE).build();
        final AuditableExecutionResult accessResult = this.registeredServiceAccessStrategyEnforcer.execute(audit);
        accessResult.throwExceptionIfNeeded();
        AuthenticationCredentialsThreadLocalBinder.bindCurrent(finalAuthentication);
        final Assertion assertion = new DefaultAssertionBuilder(finalAuthentication).with(selectedService).with(serviceTicket.getTicketGrantingTicket().getChainedAuthentications()).with(serviceTicket.isFromNewLogin()).build();
        doPublishEvent(new CasServiceTicketValidatedEvent(this, serviceTicket, assertion));
        return assertion;
    } finally {
        if (serviceTicket.isExpired()) {
            deleteTicket(serviceTicketId);
        } else {
            this.ticketRegistry.updateTicket(serviceTicket);
        }
    }
}
Also used : AuditableContext(org.apereo.cas.audit.AuditableContext) 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) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) ServiceTicket(org.apereo.cas.ticket.ServiceTicket) DefaultAssertionBuilder(org.apereo.cas.validation.DefaultAssertionBuilder) Authentication(org.apereo.cas.authentication.Authentication) CasServiceTicketValidatedEvent(org.apereo.cas.support.events.ticket.CasServiceTicketValidatedEvent) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) AuditableExecutionResult(org.apereo.cas.audit.AuditableExecutionResult) 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 4 with DefaultAssertionBuilder

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

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

the class Cas10ResponseViewTests method setUp.

@Before
public void setUp() {
    this.model = new HashMap<>();
    final List<Authentication> list = new ArrayList<>();
    list.add(CoreAuthenticationTestUtils.getAuthentication("someothername"));
    this.model.put("assertion", new DefaultAssertionBuilder(CoreAuthenticationTestUtils.getAuthentication()).with(list).with(CoreAuthenticationTestUtils.getService("TestService")).with(true).build());
}
Also used : DefaultAssertionBuilder(org.apereo.cas.validation.DefaultAssertionBuilder) Authentication(org.apereo.cas.authentication.Authentication) ArrayList(java.util.ArrayList) Before(org.junit.Before)

Aggregations

Authentication (org.apereo.cas.authentication.Authentication)6 DefaultAssertionBuilder (org.apereo.cas.validation.DefaultAssertionBuilder)6 Principal (org.apereo.cas.authentication.principal.Principal)5 Assertion (org.apereo.cas.validation.Assertion)5 HashMap (java.util.HashMap)4 DefaultPrincipalFactory (org.apereo.cas.authentication.principal.DefaultPrincipalFactory)3 Test (org.junit.Test)3 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)3 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)3 AuthenticationBuilder (org.apereo.cas.authentication.AuthenticationBuilder)2 DefaultAuthenticationBuilder (org.apereo.cas.authentication.DefaultAuthenticationBuilder)2 Service (org.apereo.cas.authentication.principal.Service)2 RegisteredService (org.apereo.cas.services.RegisteredService)2 Counted (com.codahale.metrics.annotation.Counted)1 Metered (com.codahale.metrics.annotation.Metered)1 Timed (com.codahale.metrics.annotation.Timed)1 ArrayList (java.util.ArrayList)1 LinkedHashMap (java.util.LinkedHashMap)1 AuditableContext (org.apereo.cas.audit.AuditableContext)1 AuditableExecutionResult (org.apereo.cas.audit.AuditableExecutionResult)1