protected void buildResponseBasedSingleSignOnSession(
        final Pair<? extends RequestAbstractType, MessageContext> context,
        final TicketGrantingTicket ticketGrantingTicket,
        final HttpServletRequest request,
        final HttpServletResponse response) throws Throwable {
        val authnRequest = (AuthnRequest) context.getLeft();
        val id = SamlIdPUtils.getIssuerFromSamlObject(authnRequest);
        val service = configurationContext.getWebApplicationServiceFactory().createService(id);
        service.getAttributes().put(SamlProtocolConstants.PARAMETER_ENTITY_ID, CollectionUtils.wrapList(id));
        val registeredService = configurationContext.getServicesManager().findServiceBy(service, SamlRegisteredService.class);

        val audit = AuditableContext.builder()
            .service(service)
            .authentication(ticketGrantingTicket.getAuthentication())
            .registeredService(registeredService)
            .httpRequest(request)
            .httpResponse(response)
            .build();
        val accessResult = configurationContext.getRegisteredServiceAccessStrategyEnforcer().execute(audit);
        accessResult.throwExceptionIfNeeded();

        val assertion = buildCasAssertion(ticketGrantingTicket.getAuthentication(), service, registeredService, Map.of());
        val authenticationContext = buildAuthenticationContextPair(request, response, context);
        val binding = determineProfileBinding(authenticationContext, request);

        val messageContext = authenticationContext.getRight();
        val relayState = SAMLBindingSupport.getRelayState(messageContext);
        SAMLBindingSupport.setRelayState(authenticationContext.getRight(), relayState);
        response.reset();

        val factory = (ServiceTicketFactory) getConfigurationContext().getTicketFactory().get(ServiceTicket.class);
        val st = factory.create(ticketGrantingTicket, service, false, ServiceTicket.class);
        getConfigurationContext().getTicketRegistry().addTicket(st);
        getConfigurationContext().getTicketRegistry().updateTicket(ticketGrantingTicket);
        buildSamlResponse(response, request, authenticationContext, Optional.of(assertion), binding, st.getId());
    }
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