diff --git a/lib/SimpleSAML/XML/SAML20/AuthnResponse.php b/lib/SimpleSAML/XML/SAML20/AuthnResponse.php
index 57b33a27d9763aa0fc1f7021c5d3085a549a3881..48c98a2a4e849c74a69712156d3ab5045c7c0d6d 100644
--- a/lib/SimpleSAML/XML/SAML20/AuthnResponse.php
+++ b/lib/SimpleSAML/XML/SAML20/AuthnResponse.php
@@ -14,6 +14,7 @@ class SimpleSAML_XML_SAML20_AuthnResponse extends SimpleSAML_XML_AuthnResponse {
 	const PROTOCOL = 'urn:oasis:names:tc:SAML:2.0';
 	
 	const TRANSIENT 	= 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient';
+	const PERSISTENT 	= 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent';
 	const EMAIL 		= 'urn:oasis:names:tc:SAML:2.0:nameid-format:email';
 
 	/* Namespaces used in the XML representation of this object.
@@ -682,7 +683,7 @@ class SimpleSAML_XML_SAML20_AuthnResponse extends SimpleSAML_XML_AuthnResponse {
 		/**
 		 * Handling NameID
 		 */
-		if ($nameidformat == self::EMAIL) {
+		if ( ($nameidformat == self::EMAIL) or ($nameidformat == self::PERSISTENT) ) {
 			$nameIdValue = $attributes[$spmd['simplesaml.nameidattribute']][0];
 		} else {
 			$nameIdValue = SimpleSAML_Utilities::generateID();
@@ -753,13 +754,17 @@ class SimpleSAML_XML_SAML20_AuthnResponse extends SimpleSAML_XML_AuthnResponse {
 		if (!empty($spnamequalifier)) {
 			$spnamequalifiertext = ' SPNameQualifier="' . htmlspecialchars($spnamequalifier) . '"';
 		}
+
+		if ($value == null) {
+			throw new Exception("NameID value is empty probably because of a configuration error (ie. the attribute that was configured as the simplesaml.nameidattribute setting was not found).");
+		}
 		
 		if ($type == self::EMAIL) {
 			return '<saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"' . 
 				$spnamequalifiertext . '>' . htmlspecialchars($value) . '</saml:NameID>';
 
 		} else {
-			return '<saml:NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:transient"' . 
+			return '<saml:NameID Format="' . $type . '"' . 
 				$spnamequalifiertext. '>' . htmlspecialchars($value). '</saml:NameID>';
 		}
 		
diff --git a/metadata-templates/saml20-sp-remote.php b/metadata-templates/saml20-sp-remote.php
index 76f0039a99765df9d5b20fd93eee5fe485c9d86f..8ff768f10480a06d35a004f9eebcf180d39c0c25 100644
--- a/metadata-templates/saml20-sp-remote.php
+++ b/metadata-templates/saml20-sp-remote.php
@@ -13,7 +13,7 @@
  *   - simplesaml.attributes (Will you send an attributestatement [true/false])
  *   - NameIDFormat
  *   - ForceAuthn (default: "false")
- *   - simplesaml.nameidattribute (only needed when you are using NameID format email.
+ *   - simplesaml.nameidattribute (only needed when you are using NameID format email or persistent).
  *
  *   - 'base64attributes'	=>	false,
  *   - 'simplesaml.attributes'	=>	true,