diff --git a/modules/saml2/lib/Message.php b/modules/saml2/lib/Message.php
index b80a55a978f67bcb66908049713dfe251f4214ff..e8ea3b1f2a024f0cab20def9e142bdb911a966b6 100644
--- a/modules/saml2/lib/Message.php
+++ b/modules/saml2/lib/Message.php
@@ -345,6 +345,25 @@ class sspmod_saml2_Message {
 	}
 
 
+	/**
+	 * Build a authentication response based on information in the metadata.
+	 *
+	 * @param SimpleSAML_Configuration $srcMetadata  The metadata of the sender (IdP).
+	 * @param SimpleSAML_Configuration $dstMetadata  The metadata of the recipient (SP).
+	 */
+	public static function buildResponse(SimpleSAML_Configuration $srcMetadata, SimpleSAML_Configuration $dstMetadata) {
+
+		$r = new SAML2_Response();
+
+		$r->setIssuer($srcMetadata->getString('entityid'));
+		$r->setDestination($dstMetadata->getString('AssertionConsumerService'));
+
+		self::addSign($srcMetadata, $dstMetadata, $r);
+
+		return $r;
+	}
+
+
 	/**
 	 * Process a response message.
 	 *
diff --git a/www/saml2/idp/SSOService.php b/www/saml2/idp/SSOService.php
index b8059f6c856cfe173b2579d223afcbff93e21ea0..3ed7cc7db45e2932e751a72ac8ffc7d66b913eee 100644
--- a/www/saml2/idp/SSOService.php
+++ b/www/saml2/idp/SSOService.php
@@ -67,17 +67,23 @@ function handleError(Exception $exception) {
 	$error->logWarning();
 
 	try {
+		$idpMetadata = $metadata->getMetaDataConfig($idpentityid, 'saml20-idp-hosted');
+		$spMetadata = $metadata->getMetaDataConfig($issuer, 'saml20-sp-remote');
 
-		/* Generate an SAML 2.0 AuthNResponse message
-		 * With statusCode: urn:oasis:names:tc:SAML:2.0:status:NoPassive
-		 */
-		$ar = new SimpleSAML_XML_SAML20_AuthnResponse($config, $metadata);
-		$authnResponseXML = $ar->generate($idpentityid, $issuer, $requestID, NULL, NULL, $error, $config->getValue('session.duration', 3600) );
+		$ar = sspmod_saml2_Message::buildResponse($idpMetadata, $spMetadata);
+		$ar->setInResponseTo($requestID);
+		$ar->setRelayState($relayState);
+
+		$ar->setStatus(array(
+			'Code' => $error->getStatus(),
+			'SubCode' => $error->getSubStatus(),
+			'Message' => $error->getStatusMessage(),
+			));
+
+		$binding = new SAML2_HTTPPost();
+		$binding->setDestination(sspmod_SAML2_Message::getDebugDestination());
+		$binding->send($ar);
 
-		/* Sending the AuthNResponse using HTTP-Post SAML 2.0 binding. */
-		$httppost = new SimpleSAML_Bindings_SAML20_HTTPPost($config, $metadata);
-		$httppost->sendResponse($authnResponseXML, $idpentityid, $issuer, $relayState);
-		exit();
 	} catch(Exception $e) {
 		SimpleSAML_Utilities::fatalError($session->getTrackID(), 'GENERATEAUTHNRESPONSE', $e);
 	}