diff --git a/modules/saml/lib/IdP/SAML2.php b/modules/saml/lib/IdP/SAML2.php
index 23696bf28632bf48e9319fa4114339f0c62fa37b..d3ae2037a093ec9f2390b0ed608320f8725f5936 100644
--- a/modules/saml/lib/IdP/SAML2.php
+++ b/modules/saml/lib/IdP/SAML2.php
@@ -180,6 +180,13 @@ class sspmod_saml_IdP_SAML2 {
 			} else {
 				$protocolBinding = NULL;
 			}
+
+			if (isset($_REQUEST['NameIDFormat'])) {
+				$nameIDFormat = (string)$_REQUEST['NameIDFormat'];
+			} else {
+				$nameIDFormat = NULL;
+			}
+
 			$requestId = NULL;
 			$IDPList = array();
 			$forceAuthn = FALSE;
@@ -253,6 +260,12 @@ class sspmod_saml_IdP_SAML2 {
 			$consumerURL = $request->getAssertionConsumerServiceURL();
 			$protocolBinding = $request->getProtocolBinding();
 
+			$nameIdPolicy = $request->getNameIdPolicy();
+			if (isset($nameIdPolicy['Format'])) {
+				$nameIDFormat = $nameIdPolicy['Format'];
+			} else {
+				$nameIDFormat = NULL;
+			}
 			SimpleSAML_Logger::info('SAML2.0 - IdP.SSOService: Incomming Authentication request: '. var_export($spEntityId, TRUE));
 		}
 
@@ -324,6 +337,7 @@ class sspmod_saml_IdP_SAML2 {
 			'isPassive' => $isPassive,
 			'saml:ConsumerURL' => $consumerURL,
 			'saml:Binding' => $protocolBinding,
+			'saml:NameIDFormat' => $nameIDFormat,
 		);
 
 		$idp->handleAuthenticationRequest($state);
diff --git a/modules/saml2/lib/Message.php b/modules/saml2/lib/Message.php
index ea29b2316b59e88bdb75128c1cb5ea3cb25d0fca..a5b1b349aa0d1a57571b36fc0ebcf074f30ab7d4 100644
--- a/modules/saml2/lib/Message.php
+++ b/modules/saml2/lib/Message.php
@@ -617,7 +617,16 @@ class sspmod_saml2_Message {
 
 		/* Generate the NameID for the assertion. */
 
-		$nameIdFormat = $dstMetadata->getString('NameIDFormat', 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient');
+		if (isset($state['saml:NameIDFormat'])) {
+			$nameIdFormat = $state['saml:NameIDFormat'];
+		} else {
+			$nameIdFormat = NULL;
+		}
+
+		if ($nameIdFormat === NULL || !isset($state['saml:NameID'][$nameIdFormat])) {
+			/* Either not set in request, or not set to a format we supply. Fall back to old generation method. */
+			$nameIdFormat = $dstMetadata->getString('NameIDFormat', 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient');
+		}
 
 		if (isset($state['saml:NameID'][$nameIdFormat])) {
 			$nameId = $state['saml:NameID'][$nameIdFormat];