protected XMLObject buildSamlResponse(final HttpServletResponse response,
                                          final HttpServletRequest request,
                                          final Pair<? extends RequestAbstractType, MessageContext> authenticationContext,
                                          final Optional<AuthenticatedAssertionContext> casAssertion,
                                          final String binding,
                                          final String sessionIndex) throws Exception {
        val authnRequest = (AuthnRequest) authenticationContext.getKey();
        val pair = getRegisteredServiceAndFacade(authnRequest, request);

        val entityId = pair.getValue().getEntityId();
        LOGGER.debug("Preparing SAML2 response for [{}]", entityId);
        val buildContext = SamlProfileBuilderContext.builder()
            .samlRequest(authnRequest)
            .httpRequest(request)
            .httpResponse(response)
            .authenticatedAssertion(casAssertion)
            .registeredService(pair.getKey())
            .adaptor(pair.getValue())
            .binding(binding)
            .messageContext(authenticationContext.getValue())
            .sessionIndex(sessionIndex)
            .build();
        val samlResponse = configurationContext.getResponseBuilder().build(buildContext);
        LOGGER.info("Built the SAML2 response for [{}]", entityId);
        return samlResponse;
    }
Handle SAML2 exceptions.

@param req the req
@param ex  the ex
@return the model and view
support/cas-server-support-saml-idp-web/src/main/java/org/apereo/cas/support/saml/web/idp/profile/AbstractSamlIdPProfileHandlerController.java