private void handleLogoutResponseFromFramework(
      HttpServletRequest request, HttpServletResponse response, SAMLSSOSessionDTO sessionDTO)
      throws ServletException, IOException, IdentityException {

    SAMLSSOReqValidationResponseDTO validationResponseDTO = sessionDTO.getValidationRespDTO();

    if (validationResponseDTO != null) {
      // sending LogoutRequests to other session participants
      LogoutRequestSender.getInstance()
          .sendLogoutRequests(validationResponseDTO.getLogoutRespDTO());
      SAMLSSOUtil.removeSession(sessionDTO.getSessionId(), validationResponseDTO.getIssuer());
      removeSessionDataFromCache(
          CharacterEncoder.getSafeText(request.getParameter("sessionDataKey")));

      if (validationResponseDTO.isIdPInitSLO()) {
        // redirecting to the return URL or IS logout page
        response.sendRedirect(validationResponseDTO.getReturnToURL());
      } else {
        // sending LogoutResponse back to the initiator
        sendResponse(
            request,
            response,
            sessionDTO.getRelayState(),
            validationResponseDTO.getLogoutResponse(),
            validationResponseDTO.getAssertionConsumerURL(),
            validationResponseDTO.getSubject(),
            null,
            sessionDTO.getTenantDomain());
      }
    } else {
      try {
        samlSsoService.doSingleLogout(request.getSession().getId());
      } catch (IdentityException e) {
        log.error("Error when processing the logout request!", e);
      }

      String errorResp =
          SAMLSSOUtil.buildErrorResponse(
              SAMLSSOConstants.StatusCodes.REQUESTOR_ERROR,
              "Invalid request",
              sessionDTO.getAssertionConsumerURL());
      sendNotification(
          errorResp,
          SAMLSSOConstants.Notification.INVALID_MESSAGE_STATUS,
          SAMLSSOConstants.Notification.INVALID_MESSAGE_MESSAGE,
          sessionDTO.getAssertionConsumerURL(),
          request,
          response);
    }
  }
  /**
   * This method handles authentication and sends authentication Response message back to the
   * Service Provider after successful authentication. In case of authentication failure the user is
   * prompted back for authentication.
   *
   * @param req
   * @param resp
   * @param sessionId
   * @throws IdentityException
   * @throws IOException
   * @throws ServletException
   */
  private void handleAuthenticationReponseFromFramework(
      HttpServletRequest req,
      HttpServletResponse resp,
      String sessionId,
      SAMLSSOSessionDTO sessionDTO)
      throws UserStoreException, IdentityException, IOException, ServletException {

    String sessionDataKey = CharacterEncoder.getSafeText(req.getParameter("sessionDataKey"));
    AuthenticationResult authResult = getAuthenticationResultFromCache(sessionDataKey);

    if (log.isDebugEnabled() && authResult == null) {
      log.debug("Session data is not found for key : " + sessionDataKey);
    }
    SAMLSSOReqValidationResponseDTO reqValidationDTO = sessionDTO.getValidationRespDTO();
    SAMLSSOAuthnReqDTO authnReqDTO = new SAMLSSOAuthnReqDTO();

    if (authResult == null || !authResult.isAuthenticated()) {

      if (log.isDebugEnabled() && authResult != null) {
        log.debug("Unauthenticated User");
      }

      if (reqValidationDTO.isPassive()) { // if passive

        List<String> statusCodes = new ArrayList<String>();
        statusCodes.add(SAMLSSOConstants.StatusCodes.NO_PASSIVE);
        statusCodes.add(SAMLSSOConstants.StatusCodes.IDENTITY_PROVIDER_ERROR);
        String destination = reqValidationDTO.getDestination();
        reqValidationDTO.setResponse(
            SAMLSSOUtil.buildErrorResponse(
                reqValidationDTO.getId(),
                statusCodes,
                "Cannot authenticate Subject in Passive Mode",
                destination));

        sendResponse(
            req,
            resp,
            sessionDTO.getRelayState(),
            reqValidationDTO.getResponse(),
            reqValidationDTO.getAssertionConsumerURL(),
            reqValidationDTO.getSubject(),
            null,
            sessionDTO.getTenantDomain());
        return;

      } else { // if forceAuthn or normal flow
        // TODO send a saml response with a status message.
        if (!authResult.isAuthenticated()) {
          String destination = reqValidationDTO.getDestination();
          String errorResp =
              SAMLSSOUtil.buildErrorResponse(
                  SAMLSSOConstants.StatusCodes.AUTHN_FAILURE,
                  "User authentication failed",
                  destination);
          sendNotification(
              errorResp,
              SAMLSSOConstants.Notification.EXCEPTION_STATUS,
              SAMLSSOConstants.Notification.EXCEPTION_MESSAGE,
              reqValidationDTO.getAssertionConsumerURL(),
              req,
              resp);
          return;
        } else {
          throw new IdentityException("Session data is not found for authenticated user");
        }
      }
    } else {
      populateAuthnReqDTO(req, authnReqDTO, sessionDTO, authResult);
      req.setAttribute(SAMLSSOConstants.AUTHENTICATION_RESULT, authResult);
      String relayState = null;

      if (req.getParameter(SAMLSSOConstants.RELAY_STATE) != null) {
        relayState = req.getParameter(SAMLSSOConstants.RELAY_STATE);
      } else {
        relayState = sessionDTO.getRelayState();
      }

      startTenantFlow(authnReqDTO.getTenantDomain());

      if (sessionId == null) {
        sessionId = UUIDGenerator.generateUUID();
      }

      SAMLSSOService samlSSOService = new SAMLSSOService();
      SAMLSSORespDTO authRespDTO =
          samlSSOService.authenticate(
              authnReqDTO,
              sessionId,
              authResult.isAuthenticated(),
              authResult.getAuthenticatedAuthenticators(),
              SAMLSSOConstants.AuthnModes.USERNAME_PASSWORD);

      if (authRespDTO.isSessionEstablished()) { // authenticated

        storeTokenIdCookie(sessionId, req, resp, authnReqDTO.getTenantDomain());
        removeSessionDataFromCache(
            CharacterEncoder.getSafeText(req.getParameter("sessionDataKey")));

        sendResponse(
            req,
            resp,
            relayState,
            authRespDTO.getRespString(),
            authRespDTO.getAssertionConsumerURL(),
            authRespDTO.getSubject().getAuthenticatedSubjectIdentifier(),
            authResult.getAuthenticatedIdPs(),
            sessionDTO.getTenantDomain());
      } else { // authentication FAILURE
        String errorResp = authRespDTO.getRespString();
        sendNotification(
            errorResp,
            SAMLSSOConstants.Notification.EXCEPTION_STATUS,
            SAMLSSOConstants.Notification.EXCEPTION_MESSAGE,
            authRespDTO.getAssertionConsumerURL(),
            req,
            resp);
      }
    }
  }