Prepare the request to be sent to RST2 endpoint with the saml assertion
@param $samlAssertion
@return bool|mixed|string
@throws \Exception
768169
protected function prepareRST2Request($samlAssertion)
    {

      $fileName = __DIR__ . '/xml/RST2.xml';
      if (!file_exists($fileName)) {
        throw new \Exception("The file $fileName does not exist");
      }
      $template = file_get_contents($fileName);

      $xml = new \DOMDocument();
      $xml->loadXML($template);
      $xpath = new \DOMXPath($xml);

      $samlAssertion = $xml->importNode($samlAssertion, true);
      if ($xpath->query("//*[name()='wsse:Security']")->length > 0) {
          $parentNode = $xpath->query("//wsse:Security")->item(0);
          //append "saml assertion" node to <wsse:Security> node
          $parentNode->appendChild($samlAssertion);
          return $xml->saveXML();
      }

      return NULL;
    }
1019655
public function createLogoutResponse()
    {
        return (new LogoutResponse())
            ->setStatus(new Status(new StatusCode(SamlConstants::STATUS_SUCCESS)))
            ->setID(Helper::generateID())
            ->setVersion(SamlConstants::VERSION_20)
            ->setIssuer(new Issuer($this->getMetadata()->getServiceProvider()->getEntityID()))
            ->setIssueInstant(new \DateTime());
    }
19646
public function getNameIdData()
    {
        $encryptedIdDataEntries = $this->_queryAssertion('/saml:Subject/saml:EncryptedID/xenc:EncryptedData');

        if ($encryptedIdDataEntries->length == 1) {
            $encryptedData = $encryptedIdDataEntries->item(0);

            $key = $this->_settings->getSPkey();
            $seckey = new XMLSecurityKey(XMLSecurityKey::RSA_1_5, array('type'=>'private'));
            $seckey->loadKey($key);

            $nameId = OneLogin_Saml2_Utils::decryptElement($encryptedData, $seckey);

        } else {
            $entries = $this->_queryAssertion('/saml:Subject/saml:NameID');
            if ($entries->length == 1) {
                $nameId = $entries->item(0);
            }
        }

        $nameIdData = array();

        if (!isset($nameId)) {
            $security = $this->_settings->getSecurityData();
            if ($security['wantNameId']) {
                throw new OneLogin_Saml2_ValidationError(
                    "NameID not found in the assertion of the Response",
                    OneLogin_Saml2_ValidationError::NO_NAMEID
                );
            }
        } else {
            if ($this->_settings->isStrict() && empty($nameId->nodeValue)) {
                throw new OneLogin_Saml2_ValidationError(
                    "An empty NameID value found",
                    OneLogin_Saml2_ValidationError::EMPTY_NAMEID
                );
            }
            $nameIdData['Value'] = $nameId->nodeValue;

            foreach (array('Format', 'SPNameQualifier', 'NameQualifier') as $attr) {
                if ($nameId->hasAttribute($attr)) {
                    if ($this->_settings->isStrict() && $attr == 'SPNameQualifier') {
                        $spData = $this->_settings->getSPData();
                        $spEntityId = $spData['entityId'];
                        if ($spEntityId != $nameId->getAttribute($attr)) {
                            throw new OneLogin_Saml2_ValidationError(
                                "The SPNameQualifier value mistmatch the SP entityID value.",
                                OneLogin_Saml2_ValidationError::SP_NAME_QUALIFIER_NAME_MISMATCH
                            );
                        }
                    }
                    $nameIdData[$attr] = $nameId->getAttribute($attr);
                }
            }
        }

        return $nameIdData;
    }
391128
public function formatSPCertNew()
    {
        if (isset($this->_sp['x509certNew'])) {
            $this->_sp['x509certNew'] = OneLogin_Saml2_Utils::formatCert($this->_sp['x509certNew']);
        }
    }
311870
public function receive() : ?Message
    {
        if (array_key_exists('SAMLart', $_REQUEST)) {
            $artifact = base64_decode($_REQUEST['SAMLart']);
            $endpointIndex = bin2hex(substr($artifact, 2, 2));
            $sourceId = bin2hex(substr($artifact, 4, 20));
        } else {
            throw new \Exception('Missing SAMLart parameter.');
        }

        /** @psalm-suppress UndefinedClass */
        $metadataHandler = MetaDataStorageHandler::getMetadataHandler();

        $idpMetadata = $metadataHandler->getMetaDataConfigForSha1($sourceId, 'saml20-idp-remote');

        if ($idpMetadata === null) {
            throw new \Exception('No metadata found for remote provider with SHA1 ID: '.var_export($sourceId, true));
        }

        $endpoint = null;
        foreach ($idpMetadata->getEndpoints('ArtifactResolutionService') as $ep) {
            if ($ep['index'] === hexdec($endpointIndex)) {
                $endpoint = $ep;
                break;
            }
        }

        if ($endpoint === null) {
            throw new \Exception('No ArtifactResolutionService with the correct index.');
        }

        Utils::getContainer()->getLogger()->debug("ArtifactResolutionService endpoint being used is := ".$endpoint['Location']);

        //Construct the ArtifactResolve Request
        $ar = new ArtifactResolve();

        /* Set the request attributes */

        /** @psalm-suppress UndefinedClass */
        $ar->setIssuer($this->spMetadata->getString('entityid'));
        $ar->setArtifact($_REQUEST['SAMLart']);
        $ar->setDestination($endpoint['Location']);

        // sign the request
        /** @psalm-suppress UndefinedClass */
        MSG::addSign($this->spMetadata, $idpMetadata, $ar); // Shoaib - moved from the SOAPClient.

        $soap = new SOAPClient();

        // Send message through SoapClient
        /** @var \SAML2\ArtifactResponse $artifactResponse */
        $artifactResponse = $soap->send($ar, $this->spMetadata);

        if (!$artifactResponse->isSuccess()) {
            throw new \Exception('Received error from ArtifactResolutionService.');
        }

        $xml = $artifactResponse->getAny();
        if ($xml === null) {
            /* Empty ArtifactResponse - possibly because of Artifact replay? */

            throw new \Exception('Empty ArtifactResponse received, maybe a replay?');
        }

        $samlResponse = Message::fromXML($xml);
        $samlResponse->addValidator([get_class($this), 'validateSignature'], $artifactResponse);

        if (isset($_REQUEST['RelayState'])) {
            $samlResponse->setRelayState($_REQUEST['RelayState']);
        }

        return $samlResponse;
    }
880132
public function toXML(DOMElement $parent = null) : DOMElement
    {
        if (($this->Saml2IssuerShowAll && ($this->Format === Constants::NAMEID_ENTITY))
            || ($this->Format !== Constants::NAMEID_ENTITY)
        ) {
            return parent::toXML($parent);
        }

        /*
         * if $this->Saml2IssuerShowAll is set false
         * From saml-core-2.0-os 8.3.6, when the entity Format is used: "The NameQualifier, SPNameQualifier, and
         * SPProvidedID attributes MUST be omitted."
         * if $this->isSaml2IssuerShowAll() is set true when the entity Format is used: "The NameQualifier,
         * SPNameQualifier, and SPProvidedID attributes are not omitted."
         */

        if ($parent === null) {
            $parent = DOMDocumentFactory::create();
            $doc = $parent;
        } else {
            $doc = $parent->ownerDocument;
        }
        $element = $doc->createElementNS(Constants::NS_SAML, 'saml:Issuer');
        $parent->appendChild($element);

        if (empty($this->value)) {
            throw new \Exception("Cannot convert Issuer to XML with no value.");
        }
        $value = $element->ownerDocument->createTextNode($this->value);
        $element->appendChild($value);

        return $element;
    }
405895
public function setStatus($sStatus)
    {
        if (!$this->bIsLocked) {

            $aStatuses = $this->getStatuses();
            if (!in_array($sStatus, $aStatuses)) {
                throw new ResponseException('"' . $sStatus . '" is an invalid response status.', 1);
            }

            $this->sStatus = $sStatus;
        }

        return $this;
    }
243216
protected function attemptAuthentication(Request $request)
    {
        $samlResponse = $this->receiveSamlResponse();

        $token = new SamlSpResponseToken($samlResponse, $this->providerKey);

        $token = $this->authenticationManager->authenticate($token);

        return $token;
    }
1297857
public function build(): SetIgnoreCertificateErrorsRequest
	{
		$instance = new SetIgnoreCertificateErrorsRequest();
		if ($this->ignore === null) {
			throw new BuilderException('Property [ignore] is required.');
		}
		$instance->ignore = $this->ignore;
		return $instance;
	}
349853
public function send(Request $request)
    {
        $response   = new GetIndexResponse();
        $rpbGetReq  = $this->createRpbMessage($request);
        $rpbGetResp = $this->client->send($rpbGetReq, RiakMessageCodes::YOKOZUNA_INDEX_GET_REQ, RiakMessageCodes::YOKOZUNA_INDEX_GET_RESP);

        if ( ! $rpbGetResp instanceof RpbYokozunaIndexGetResp) {
            return $response;
        }

        if ( ! $rpbGetResp->hasIndex()) {
            return $response;
        }

        $rpbIndex = is_array($rpbGetResp->index)
            ? reset($rpbGetResp->index)
            : $rpbGetResp->index;

        $response->nVal   = $rpbIndex->n_val;
        $response->name   = $rpbIndex->name;
        $response->schema = $rpbIndex->schema;

        return $response;
    }
1330191
protected function prepareResponse($result)
    {
        $this->checkForCurlErrors();

        $response = array();
        $response["data"] = $this->getSerializer()->deserialize($result);
        $response["status"] = $this->getStatusCode();


        if ($response['status'] >= 400 && $response['status'] < 500) {
            $statusCode = $response['status'];
            $exceptionText = "{$statusCode} Client Exception: {$result}";

            throw new ClientErrorException($exceptionText, $statusCode);
        } else if ($response['status'] >= 500) {
            $statusCode = $response['status'];
            $exceptionText = "{$statusCode} Server Exception: {$result}";

            throw new ServerErrorException($exceptionText, $statusCode);
        }

        return $response;
    }
783733
public void encodeSamlResponse(final Response samlResponse, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
        this.samlObjectBuilder.encodeSamlResponse(response, request, samlResponse);
    }
455858
public function fromException( Exception $exception )
    {
        return $this->generateResponse(
            xmlrpc_encode_request(
                null,
                array(
                    'faultCode' => $exception->getCode(),
                    'faultString' => $exception->getMessage()
                )
            )
        );
    }
685603
public static function fromXML(\DOMElement $xml) : Message
    {
        if ($xml->namespaceURI !== Constants::NS_SAMLP) {
            throw new \Exception('Unknown namespace of SAML message: '.var_export($xml->namespaceURI, true));
        }

        switch ($xml->localName) {
            case 'AttributeQuery':
                return new AttributeQuery($xml);
            case 'AuthnRequest':
                return new AuthnRequest($xml);
            case 'LogoutResponse':
                return new LogoutResponse($xml);
            case 'LogoutRequest':
                return new LogoutRequest($xml);
            case 'Response':
                return new Response($xml);
            case 'ArtifactResponse':
                return new ArtifactResponse($xml);
            case 'ArtifactResolve':
                return new ArtifactResolve($xml);
            default:
                throw new \Exception('Unknown SAML message: '.var_export($xml->localName, true));
        }
    }
126837
public function tokenAction()
    {
        // Can't do anything if not HTTP request...
        if (!$this->request instanceof HttpRequest) {
            return null;
        }

        // Currently, ZF2 Http Request object is not PSR-7 compliant, therefore we need to create a new one from
        // globals, and then convert the response back to ZF2 format

        $request  = ServerRequestFactory::fromGlobals();
        $response = $this->authorizationServer->handleTokenRequest($request);

        return $this->convertToZfResponse($response);
    }
949566
protected function _queryAssertion($assertionXpath)
    {
        if ($this->encrypted) {
            $xpath = new DOMXPath($this->decryptedDocument);
        } else {
            $xpath = new DOMXPath($this->document);
        }

        $xpath->registerNamespace('samlp', OneLogin_Saml2_Constants::NS_SAMLP);
        $xpath->registerNamespace('saml', OneLogin_Saml2_Constants::NS_SAML);
        $xpath->registerNamespace('ds', OneLogin_Saml2_Constants::NS_DS);
        $xpath->registerNamespace('xenc', OneLogin_Saml2_Constants::NS_XENC);

        $assertionNode = '/samlp:Response/saml:Assertion';
        $signatureQuery = $assertionNode . '/ds:Signature/ds:SignedInfo/ds:Reference';
        $assertionReferenceNode = $xpath->query($signatureQuery)->item(0);
        if (!$assertionReferenceNode) {
            // is the response signed as a whole?
            $signatureQuery = '/samlp:Response/ds:Signature/ds:SignedInfo/ds:Reference';
            $responseReferenceNode = $xpath->query($signatureQuery)->item(0);
            if ($responseReferenceNode) {
                $uri = $responseReferenceNode->attributes->getNamedItem('URI')->nodeValue;
                if (empty($uri)) {
                    $id = $responseReferenceNode->parentNode->parentNode->parentNode->attributes->getNamedItem('ID')->nodeValue;
                } else {
                    $id = substr($responseReferenceNode->attributes->getNamedItem('URI')->nodeValue, 1);
                }
                $nameQuery = "/samlp:Response[@ID='$id']/saml:Assertion" . $assertionXpath;
            } else {
                $nameQuery = "/samlp:Response/saml:Assertion" . $assertionXpath;
            }
        } else {
            $uri = $assertionReferenceNode->attributes->getNamedItem('URI')->nodeValue;
            if (empty($uri)) {
                $id = $assertionReferenceNode->parentNode->parentNode->parentNode->attributes->getNamedItem('ID')->nodeValue;
            } else {
                $id = substr($assertionReferenceNode->attributes->getNamedItem('URI')->nodeValue, 1);
            }
            $nameQuery = $assertionNode."[@ID='$id']" . $assertionXpath;
        }

        return $xpath->query($nameQuery);
    }
1214520
protected function sendSamlResponse(Response $response)
    {
        $bindingFactory = new \LightSaml\Binding\BindingFactory();
        $postBinding = $bindingFactory->create(\LightSaml\SamlConstants::BINDING_SAML2_HTTP_POST);
        $messageContext = new \LightSaml\Context\Profile\MessageContext();
        $messageContext->setMessage($response)->asResponse();
        /** @var \Symfony\Component\HttpFoundation\Response $httpResponse */
        $httpResponse = $postBinding->send($messageContext);
        print $httpResponse->getContent()."\n\n";
    }