// Process a successful SAML response. private void ProcessSuccessSAMLResponse(SAMLResponse samlResponse, string relayState) { Trace.Write("SP", "Processing successful SAML response"); // Load the decryption key. X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.SPX509Certificate]; // Extract the asserted identity from the SAML response. SAMLAssertion samlAssertion = null; if (samlResponse.GetAssertions().Count > 0) { samlAssertion = samlResponse.GetAssertions()[0]; } else if (samlResponse.GetEncryptedAssertions().Count > 0) { Trace.Write("SP", "Decrypting assertion"); samlAssertion = samlResponse.GetEncryptedAssertions()[0].Decrypt(x509Certificate.PrivateKey, null, null); } else { throw new ArgumentException("No assertions in response"); } // Get the subject name identifier. string userName = null; if (samlAssertion.Subject.NameID != null) { userName = samlAssertion.Subject.NameID.NameIdentifier; } else if (samlAssertion.Subject.EncryptedID != null) { Trace.Write("SP", "Decrypting ID"); NameID nameID = samlAssertion.Subject.EncryptedID.Decrypt(x509Certificate.PrivateKey, null, null); userName = nameID.NameIdentifier; } else { throw new ArgumentException("No name in subject"); } // Get the originally requested resource URL from the relay state. RelayState cachedRelayState = RelayStateCache.Remove(relayState); if (cachedRelayState == null) { throw new ArgumentException("Invalid relay state"); } // Create a login context for the asserted identity. FormsAuthentication.SetAuthCookie(userName, false); // Redirect to the originally requested resource URL. Response.Redirect(cachedRelayState.ResourceURL, false); Trace.Write("SP", "Processed successful SAML response"); }
// Process the SAML response. private void ProcessSAMLResponse(SAMLResponse samlResponse, string relayState) { Trace.Write("SP", "Processing SAML response"); // Check whether the SAML response indicates success. if (!samlResponse.IsSuccess()) { throw new ArgumentException("Received error response"); } // Extract the asserted identity from the SAML response. SAMLAssertion samlAssertion = null; if (samlResponse.GetAssertions().Count > 0) { samlAssertion = samlResponse.GetAssertions()[0]; } else { throw new ArgumentException("No assertions in response"); } // Enforce single use of the SAML assertion. if (!AssertionIDCache.Add(samlAssertion)) { throw new ArgumentException("The SAML assertion has already been used"); } // Get the subject name identifier. string userName = null; if (samlAssertion.Subject.NameID != null) { userName = samlAssertion.Subject.NameID.NameIdentifier; } else { throw new ArgumentException("No name in subject"); } // Create a login context for the asserted identity. FormsAuthentication.SetAuthCookie(userName, false); // Redirect to the requested URL. Response.Redirect(relayState, false); Trace.Write("SP", "Processed successful SAML response"); }
public ActionResult UploadSaml(FormCollection formCollection) { var attributes = new List <SAMLAttribute>(); var errorMessages = new List <string>(); var xmlDoc = null as XmlDocument; SessionHelper.Set(SamlAttributesSessionKey, null); SessionHelper.Set(SamlErrorMessagesSessionKey, null); if (Request != null) { var file = Request.Files["SamlFile"]; if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName)) { try { xmlDoc = new XmlDocument(); xmlDoc.Load(file.InputStream); var samlValidator = new SAMLValidator(); var isValid = samlValidator.Validate(xmlDoc); if (!isValid) { errorMessages.AddRange(samlValidator.Warnings.Select(warning => string.Format("Warning:, {0}", warning.Message))); errorMessages.AddRange(samlValidator.Errors.Select(error => error.Message)); } if (SAMLMessageSignature.IsSigned(xmlDoc.DocumentElement)) { if (!SAMLMessageSignature.Verify(xmlDoc.DocumentElement)) { errorMessages.Add(string.Format("Failed to verify SAML response signature. [{0}]", xmlDoc.OuterXml)); } } var samlResponse = new SAMLResponse(xmlDoc.DocumentElement); var assertions = samlResponse.GetAssertions(); var encryptedAssertions = samlResponse.GetEncryptedAssertions(); var signedAssertions = samlResponse.GetSignedAssertions(); var x509CertificateFilePath = Path.Combine(HttpRuntime.AppDomainAppPath, SAMLConfiguration.Current.ServiceProviderConfiguration.CertificateFile); var x509Certificate = new X509Certificate2(x509CertificateFilePath, SAMLConfiguration.Current.ServiceProviderConfiguration.CertificatePassword); encryptedAssertions.ForEach(a => { var decryptedAssertion = a.DecryptToXml(x509Certificate); assertions.Add(new SAMLAssertion(decryptedAssertion)); }); signedAssertions.ForEach(a => { if (SAMLAssertionSignature.IsSigned(a)) { if (!SAMLAssertionSignature.Verify(a)) { errorMessages.Add(string.Format("Failed to verify SAML assertion signature. [{0}]", a.OuterXml)); } } assertions.Add(new SAMLAssertion(a)); }); assertions.ForEach(a => { var nameId = a.GetNameID(); if (!string.IsNullOrEmpty(nameId)) { attributes.Add("NameId", nameId); } a.GetAttributeStatements().ForEach( s => attributes.AddRange(from object attribute in s.Attributes select attribute as SAMLAttribute)); }); } catch (Exception ex) { var saml = xmlDoc != null ? xmlDoc.OuterXml : string.Empty; _logger.Log(ex); errorMessages.Add(string.Format("{0} [{1}]", ex.Message, saml)); } } } SessionHelper.Set(SamlAttributesSessionKey, attributes.ToArray()); SessionHelper.Set(SamlErrorMessagesSessionKey, errorMessages); return(Redirect(TestTargetUrl)); }
// Process a successful SAML response. private void ProcessSuccessSAMLResponse(SAMLResponse samlResponse, string relayState) { //Processing successful SAML response // Load the decryption key. X509Certificate2 x509Certificate = GetSelerixCertificate(); // Extract the asserted identity from the SAML response. SAMLAssertion samlAssertion = null; if (samlResponse.GetAssertions().Count > 0) { samlAssertion = samlResponse.GetAssertions()[0]; } else if (samlResponse.GetEncryptedAssertions().Count > 0) { //"Decrypting assertion"); samlAssertion = samlResponse.GetEncryptedAssertions()[0].Decrypt(x509Certificate.PrivateKey, null); } else if (samlResponse.GetSignedAssertions().Count > 0) { samlAssertion = new SAMLAssertion(samlResponse.GetSignedAssertions()[0]); } else { throw new ArgumentException("No assertions in response"); } // Get the subject name identifier. string userName = null; if (samlAssertion.Subject.NameID != null) { userName = samlAssertion.Subject.NameID.NameIdentifier; } else if (samlAssertion.Subject.EncryptedID != null) { //"Decrypting ID"); NameID nameID = samlAssertion.Subject.EncryptedID.Decrypt(x509Certificate.PrivateKey, null); userName = nameID.NameIdentifier; } else { throw new ArgumentException("No name in subject"); } Dictionary <string, string> outputData = new Dictionary <string, string>(); foreach (AttributeStatement attributeStatement in samlAssertion.GetAttributeStatements()) { foreach (SAMLAttribute samlAttribute in attributeStatement.GetUnencryptedAttributes()) { foreach (AttributeValue attributeValue in samlAttribute.Values) { if (!outputData.ContainsKey(samlAttribute.Name)) { outputData.Add(samlAttribute.Name, attributeValue.ToString()); } else { outputData[samlAttribute.Name] = attributeValue.ToString(); } } } foreach (EncryptedAttribute encryptedAttribute in attributeStatement.GetEncryptedAttributes()) { SAMLAttribute samlAttribute = encryptedAttribute.Decrypt(x509Certificate.PrivateKey, null); foreach (AttributeValue attributeValue in samlAttribute.Values) { if (!outputData.ContainsKey(samlAttribute.Name)) { outputData.Add(samlAttribute.Name, attributeValue.ToString()); } else { outputData[samlAttribute.Name] = attributeValue.ToString(); } } } } // prevent the output of aspx page from being cached by the browser Response.AddHeader("Cache-Control", "no-cache"); Response.AddHeader("Pragma", "no-cache"); if (outputData.ContainsKey("Transmittal")) { Session["Transmittal"] = Selerix.Foundation.Data.SerializationHelper.DeserializeFromString(outputData["Transmittal"], typeof(Transmittal)); } else { Session["Transmittal"] = null; } Session["SAMLParameters"] = outputData; Response.Redirect("~/ShowTransmittal.aspx", false); //"Processed successful SAML response"); }
// Process a successful SAML response. private void ProcessSuccessSAMLResponse(SAMLResponse samlResponse, string relayState) { Trace.Write("SP", "Processing successful SAML response"); // Extract the asserted identity from the SAML response. // The SAML assertion may be signed or encrypted and signed. SAMLAssertion samlAssertion = null; if (samlResponse.GetAssertions().Count > 0) { samlAssertion = samlResponse.GetAssertions()[0]; } else if (samlResponse.GetSignedAssertions().Count > 0) { Trace.Write("SP", "Verifying assertion signature"); XmlElement samlAssertionXml = samlResponse.GetSignedAssertions()[0]; // Verify the assertion signature. The embedded signing certificate is used. if (!SAMLAssertionSignature.Verify(samlAssertionXml)) { throw new ArgumentException("The SAML assertion signature failed to verify."); } samlAssertion = new SAMLAssertion(samlAssertionXml); } else if (samlResponse.GetEncryptedAssertions().Count > 0) { Trace.Write("SP", "Decrypting assertion"); // Load the decryption key. X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.SPX509Certificate]; // Decrypt the encrypted assertion. XmlElement samlAssertionXml = samlResponse.GetEncryptedAssertions()[0].DecryptToXml(x509Certificate.PrivateKey, null, null); if (SAMLAssertionSignature.IsSigned(samlAssertionXml)) { Trace.Write("SP", "Verifying assertion signature"); // Verify the assertion signature. The embedded signing certificate is used. if (!SAMLAssertionSignature.Verify(samlAssertionXml)) { throw new ArgumentException("The SAML assertion signature failed to verify."); } } samlAssertion = new SAMLAssertion(samlAssertionXml); } else { throw new ArgumentException("No assertions in response"); } // Get the subject name identifier. string userName = null; if (samlAssertion.Subject.NameID != null) { userName = samlAssertion.Subject.NameID.NameIdentifier; } if (string.IsNullOrEmpty(userName)) { throw new ArgumentException("The SAML assertion doesn't contain a subject name."); } // Create a login context for the asserted identity. Trace.Write("SP", "Automatically logging in user " + userName); FormsAuthentication.SetAuthCookie(userName, false); // Get the originally requested resource URL from the relay state, if any. string redirectURL = "~/"; RelayState cachedRelayState = RelayStateCache.Remove(relayState); if (cachedRelayState != null) { redirectURL = cachedRelayState.ResourceURL; } // Redirect to the originally requested resource URL, if any, or the default page. Trace.Write("SP", "Redirecting to " + redirectURL); Response.Redirect(redirectURL, false); Trace.Write("SP", "Processed successful SAML response"); }