Search in sources :

Example 61 with Issuer

use of org.opensaml.saml.saml2.core.Issuer in project cas by apereo.

the class SLOSamlIdPPostProfileHandlerControllerTests method verifyOperation.

@Test
@Order(1)
public void verifyOperation() throws Exception {
    val request = new MockHttpServletRequest();
    request.setMethod("POST");
    val response = new MockHttpServletResponse();
    val service = getSamlRegisteredServiceFor(false, false, false, "https://cassp.example.org");
    servicesManager.save(service);
    var builder = (SAMLObjectBuilder) openSamlConfigBean.getBuilderFactory().getBuilder(LogoutRequest.DEFAULT_ELEMENT_NAME);
    var logoutRequest = (LogoutRequest) builder.buildObject();
    builder = (SAMLObjectBuilder) openSamlConfigBean.getBuilderFactory().getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
    val issuer = (Issuer) builder.buildObject();
    issuer.setValue(service.getServiceId());
    logoutRequest.setIssuer(issuer);
    val adaptor = SamlRegisteredServiceServiceProviderMetadataFacade.get(samlRegisteredServiceCachingMetadataResolver, service, service.getServiceId()).get();
    logoutRequest = samlIdPObjectSigner.encode(logoutRequest, service, adaptor, response, request, SAMLConstants.SAML2_POST_BINDING_URI, logoutRequest, new MessageContext());
    val xml = SamlUtils.transformSamlObject(openSamlConfigBean, logoutRequest).toString();
    request.addParameter(SamlProtocolConstants.PARAMETER_SAML_REQUEST, EncodingUtils.encodeBase64(xml));
    controller.handleSaml2ProfileSLOPostRequest(response, request);
    assertEquals(HttpStatus.SC_OK, response.getStatus());
}
Also used : lombok.val(lombok.val) SAMLObjectBuilder(org.opensaml.saml.common.SAMLObjectBuilder) Issuer(org.opensaml.saml.saml2.core.Issuer) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) LogoutRequest(org.opensaml.saml.saml2.core.LogoutRequest) MessageContext(org.opensaml.messaging.context.MessageContext) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) TestMethodOrder(org.junit.jupiter.api.TestMethodOrder) Order(org.junit.jupiter.api.Order) Test(org.junit.jupiter.api.Test)

Example 62 with Issuer

use of org.opensaml.saml.saml2.core.Issuer in project cas by apereo.

the class SamlProfileSaml2ResponseBuilder method buildResponse.

@Override
public Response buildResponse(final Assertion assertion, final SamlProfileBuilderContext context) throws Exception {
    val id = '_' + String.valueOf(RandomUtils.nextLong());
    val samlResponse = newResponse(id, ZonedDateTime.now(ZoneOffset.UTC), context.getSamlRequest().getID(), null);
    samlResponse.setVersion(SAMLVersion.VERSION_20);
    val issuerId = FunctionUtils.doIf(StringUtils.isNotBlank(context.getRegisteredService().getIssuerEntityId()), context.getRegisteredService()::getIssuerEntityId, Unchecked.supplier(() -> {
        val criteriaSet = new CriteriaSet(new EvaluableEntityRoleEntityDescriptorCriterion(IDPSSODescriptor.DEFAULT_ELEMENT_NAME), new SamlIdPSamlRegisteredServiceCriterion(context.getRegisteredService()));
        LOGGER.trace("Resolving entity id from SAML2 IdP metadata to determine issuer for [{}]", context.getRegisteredService().getName());
        val entityDescriptor = Objects.requireNonNull(getConfigurationContext().getSamlIdPMetadataResolver().resolveSingle(criteriaSet));
        return entityDescriptor.getEntityID();
    })).get();
    samlResponse.setIssuer(buildSamlResponseIssuer(issuerId));
    val acs = SamlIdPUtils.determineEndpointForRequest(Pair.of(context.getSamlRequest(), context.getMessageContext()), context.getAdaptor(), context.getBinding());
    val location = StringUtils.isBlank(acs.getResponseLocation()) ? acs.getLocation() : acs.getResponseLocation();
    samlResponse.setDestination(location);
    if (getConfigurationContext().getCasProperties().getAuthn().getSamlIdp().getCore().isAttributeQueryProfileEnabled()) {
        storeAttributeQueryTicketInRegistry(assertion, context);
    }
    val finalAssertion = encryptAssertion(assertion, context);
    if (finalAssertion instanceof EncryptedAssertion) {
        LOGGER.trace("Built assertion is encrypted, so the response will add it to the encrypted assertions collection");
        samlResponse.getEncryptedAssertions().add(EncryptedAssertion.class.cast(finalAssertion));
    } else {
        LOGGER.trace("Built assertion is not encrypted, so the response will add it to the assertions collection");
        samlResponse.getAssertions().add(Assertion.class.cast(finalAssertion));
    }
    val status = newStatus(StatusCode.SUCCESS, null);
    samlResponse.setStatus(status);
    SamlUtils.logSamlObject(this.openSamlConfigBean, samlResponse);
    if (context.getRegisteredService().isSignResponses()) {
        LOGGER.debug("SAML entity id [{}] indicates that SAML responses should be signed", context.getAdaptor().getEntityId());
        val samlResponseSigned = getConfigurationContext().getSamlObjectSigner().encode(samlResponse, context.getRegisteredService(), context.getAdaptor(), context.getHttpResponse(), context.getHttpRequest(), context.getBinding(), context.getSamlRequest(), context.getMessageContext());
        SamlUtils.logSamlObject(openSamlConfigBean, samlResponseSigned);
        return samlResponseSigned;
    }
    return samlResponse;
}
Also used : lombok.val(lombok.val) EvaluableEntityRoleEntityDescriptorCriterion(org.opensaml.saml.metadata.criteria.entity.impl.EvaluableEntityRoleEntityDescriptorCriterion) SamlIdPSamlRegisteredServiceCriterion(org.apereo.cas.support.saml.idp.metadata.locator.SamlIdPSamlRegisteredServiceCriterion) EncryptedAssertion(org.opensaml.saml.saml2.core.EncryptedAssertion) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) EncryptedAssertion(org.opensaml.saml.saml2.core.EncryptedAssertion) Assertion(org.opensaml.saml.saml2.core.Assertion)

Example 63 with Issuer

use of org.opensaml.saml.saml2.core.Issuer in project cas by apereo.

the class ECPSamlIdPProfileHandlerController method handleEcpRequest.

/**
 * Handle ecp request.
 *
 * @param context    the context
 * @param credential the credential
 * @throws Exception the exception
 */
protected void handleEcpRequest(final SamlProfileBuilderContext context, final Credential credential) throws Exception {
    LOGGER.debug("Handling ECP request for SOAP context [{}]", context.getMessageContext());
    val envelope = context.getMessageContext().getSubcontext(SOAP11Context.class).getEnvelope();
    SamlUtils.logSamlObject(getConfigurationContext().getOpenSamlConfigBean(), envelope);
    val authnRequest = (AuthnRequest) context.getMessageContext().getMessage();
    val authenticationContext = Pair.of(authnRequest, context.getMessageContext());
    try {
        LOGGER.trace("Verifying ECP authentication request [{}]", authnRequest);
        val serviceRequest = verifySamlAuthenticationRequest(authenticationContext, context.getHttpRequest());
        LOGGER.trace("Attempting to authenticate ECP request for credential id [{}]", credential.getId());
        val authentication = authenticateEcpRequest(credential, authenticationContext);
        LOGGER.debug("Authenticated [{}] successfully with authenticated principal [{}]", credential.getId(), authentication.getPrincipal());
        LOGGER.trace("Building ECP SAML response for [{}]", credential.getId());
        val issuer = SamlIdPUtils.getIssuerFromSamlObject(authnRequest);
        val service = getConfigurationContext().getWebApplicationServiceFactory().createService(issuer);
        val casAssertion = buildCasAssertion(authentication, service, serviceRequest.getKey(), new LinkedHashMap<>(0));
        LOGGER.trace("CAS assertion to use for building ECP SAML2 response is [{}]", casAssertion);
        buildSamlResponse(context.getHttpResponse(), context.getHttpRequest(), authenticationContext, casAssertion, context.getBinding());
    } catch (final AuthenticationException e) {
        LoggingUtils.error(LOGGER, e);
        val error = e.getHandlerErrors().values().stream().map(Throwable::getMessage).filter(Objects::nonNull).collect(Collectors.joining(","));
        buildEcpFaultResponse(context, error);
    } catch (final Exception e) {
        LoggingUtils.error(LOGGER, e);
        buildEcpFaultResponse(context, e.getMessage());
    }
}
Also used : lombok.val(lombok.val) SOAP11Context(org.opensaml.soap.messaging.context.SOAP11Context) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) Objects(java.util.Objects) AuthenticationException(org.apereo.cas.authentication.AuthenticationException)

Example 64 with Issuer

use of org.opensaml.saml.saml2.core.Issuer in project cas by apereo.

the class SamlIdPSaml1ArtifactResolutionProfileHandlerController method handlePostRequest.

/**
 * Handle post request.
 *
 * @param response the response
 * @param request  the request
 * @throws Exception the exception
 */
@PostMapping(path = SamlIdPConstants.ENDPOINT_SAML1_SOAP_ARTIFACT_RESOLUTION)
protected void handlePostRequest(final HttpServletResponse response, final HttpServletRequest request) throws Exception {
    val ctx = decodeSoapRequest(request);
    val artifactMsg = (ArtifactResolve) ctx.getMessage();
    try {
        val issuer = Objects.requireNonNull(artifactMsg).getIssuer().getValue();
        val registeredService = verifySamlRegisteredService(issuer);
        val adaptor = getSamlMetadataFacadeFor(registeredService, artifactMsg);
        if (adaptor.isEmpty()) {
            throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, "Cannot find metadata linked to " + issuer);
        }
        val facade = adaptor.get();
        verifyAuthenticationContextSignature(ctx, request, artifactMsg, facade, registeredService);
        val artifactId = artifactMsg.getArtifact().getValue();
        val factory = (SamlArtifactTicketFactory) getConfigurationContext().getTicketFactory().get(SamlArtifactTicket.class);
        val ticketId = factory.createTicketIdFor(artifactId);
        val ticket = getConfigurationContext().getTicketRegistry().getTicket(ticketId, SamlArtifactTicket.class);
        if (ticket == null) {
            throw new InvalidTicketException(ticketId);
        }
        val issuerService = getConfigurationContext().getWebApplicationServiceFactory().createService(issuer);
        val casAssertion = buildCasAssertion(ticket.getTicketGrantingTicket().getAuthentication(), issuerService, registeredService, CollectionUtils.wrap("artifact", ticket));
        val buildContext = SamlProfileBuilderContext.builder().samlRequest(artifactMsg).httpRequest(request).httpResponse(response).authenticatedAssertion(casAssertion).registeredService(registeredService).adaptor(facade).binding(SAMLConstants.SAML2_ARTIFACT_BINDING_URI).messageContext(ctx).build();
        getConfigurationContext().getResponseBuilder().build(buildContext);
    } catch (final Exception e) {
        LoggingUtils.error(LOGGER, e);
        request.setAttribute(SamlIdPConstants.REQUEST_ATTRIBUTE_ERROR, "Unable to build SOAP response: " + StringUtils.defaultString(e.getMessage()));
        val buildContext = SamlProfileBuilderContext.builder().samlRequest(artifactMsg).httpRequest(request).httpResponse(response).binding(SAMLConstants.SAML2_ARTIFACT_BINDING_URI).messageContext(ctx).build();
        getConfigurationContext().getSamlFaultResponseBuilder().build(buildContext);
    }
}
Also used : lombok.val(lombok.val) ArtifactResolve(org.opensaml.saml.saml2.core.ArtifactResolve) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) SamlArtifactTicket(org.apereo.cas.ticket.artifact.SamlArtifactTicket) SamlArtifactTicketFactory(org.apereo.cas.ticket.artifact.SamlArtifactTicketFactory) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 65 with Issuer

use of org.opensaml.saml.saml2.core.Issuer in project cas by apereo.

the class AbstractSamlIdPProfileHandlerController method singleSignOnSessionExists.

/**
 * Single sign on session exists.
 *
 * @param pair     the pair
 * @param request  the request
 * @param response the response
 * @return the boolean
 */
protected Optional<TicketGrantingTicket> singleSignOnSessionExists(final Pair<? extends SignableSAMLObject, MessageContext> pair, final HttpServletRequest request, final HttpServletResponse response) {
    val authnRequest = AuthnRequest.class.cast(pair.getLeft());
    if (authnRequest.isForceAuthn()) {
        LOGGER.trace("Authentication request asks for forced authn. Ignoring existing single sign-on session, if any");
        return Optional.empty();
    }
    val cookie = configurationContext.getTicketGrantingTicketCookieGenerator().retrieveCookieValue(request);
    if (StringUtils.isBlank(cookie)) {
        LOGGER.trace("Single sign-on session cannot be found or determined. Ignoring single sign-on session");
        return Optional.empty();
    }
    val ticketGrantingTicket = configurationContext.getTicketRegistrySupport().getTicketGrantingTicket(cookie);
    if (ticketGrantingTicket == null) {
        LOGGER.debug("Authentication transaction linked to single sign-on session cannot determined.");
        return Optional.empty();
    }
    val authn = ticketGrantingTicket.getAuthentication();
    LOGGER.debug("Located single sign-on authentication for principal [{}]", authn.getPrincipal());
    val issuer = SamlIdPUtils.getIssuerFromSamlObject(authnRequest);
    val service = configurationContext.getWebApplicationServiceFactory().createService(issuer);
    val registeredService = configurationContext.getServicesManager().findServiceBy(service);
    val ssoRequest = SingleSignOnParticipationRequest.builder().httpServletRequest(request).build().attribute(Service.class.getName(), service).attribute(RegisteredService.class.getName(), registeredService).attribute(Issuer.class.getName(), issuer).attribute(Authentication.class.getName(), authn).attribute(TicketGrantingTicket.class.getName(), cookie).attribute(AuthnRequest.class.getName(), authnRequest);
    val ssoStrategy = configurationContext.getSingleSignOnParticipationStrategy();
    LOGGER.debug("Checking for single sign-on participation for issuer [{}]", issuer);
    val ssoAvailable = ssoStrategy.supports(ssoRequest) && ssoStrategy.isParticipating(ssoRequest);
    return ssoAvailable ? Optional.of(ticketGrantingTicket) : Optional.empty();
}
Also used : lombok.val(lombok.val) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) RegisteredService(org.apereo.cas.services.RegisteredService) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) Authentication(org.apereo.cas.authentication.Authentication)

Aggregations

Issuer (org.opensaml.saml.saml2.core.Issuer)79 Response (org.opensaml.saml.saml2.core.Response)59 DateTime (org.joda.time.DateTime)57 Test (org.junit.jupiter.api.Test)37 AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)36 Element (org.w3c.dom.Element)34 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)32 lombok.val (lombok.val)28 SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)26 Document (org.w3c.dom.Document)25 Status (org.opensaml.saml.saml2.core.Status)24 Assertion (org.opensaml.saml.saml2.core.Assertion)22 SAMLCallback (org.apache.wss4j.common.saml.SAMLCallback)20 SubjectConfirmationDataBean (org.apache.wss4j.common.saml.bean.SubjectConfirmationDataBean)20 SAMLObjectBuilder (org.opensaml.saml.common.SAMLObjectBuilder)17 LogoutRequest (org.opensaml.saml.saml2.core.LogoutRequest)16 InputStream (java.io.InputStream)15 IssuerBuilder (org.opensaml.saml.saml2.core.impl.IssuerBuilder)15 Crypto (org.apache.wss4j.common.crypto.Crypto)14 KeyStore (java.security.KeyStore)13