// Create a SAML response with the user's local identity, if any, or indicating an error. private SAMLResponse CreateSAMLResponse(SSOState ssoState) { Trace.Write("IdP", "Creating SAML response"); SAMLResponse samlResponse = new SAMLResponse(); string issuerURL = CreateAbsoluteURL("~/"); Issuer issuer = new Issuer(issuerURL); samlResponse.Issuer = issuer; if (User.Identity.IsAuthenticated) { samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null); SAMLAssertion samlAssertion = new SAMLAssertion(); samlAssertion.Issuer = issuer; Subject subject = new Subject(new NameID(User.Identity.Name)); SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer); SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData(); subjectConfirmationData.InResponseTo = ssoState.authnRequest.ID; subjectConfirmationData.Recipient = ssoState.assertionConsumerServiceURL; subjectConfirmation.SubjectConfirmationData = subjectConfirmationData; subject.SubjectConfirmations.Add(subjectConfirmation); samlAssertion.Subject = subject; AuthnStatement authnStatement = new AuthnStatement(); authnStatement.AuthnContext = new AuthnContext(); authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Password); samlAssertion.Statements.Add(authnStatement); // Attributes may be included in the SAML assertion. AttributeStatement attributeStatement = new AttributeStatement(); attributeStatement.Attributes.Add(new SAMLAttribute("Membership", SAMLIdentifiers.AttributeNameFormats.Basic, null, "Gold")); samlAssertion.Statements.Add(attributeStatement); samlResponse.Assertions.Add(samlAssertion); } else { samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Responder, SAMLIdentifiers.SecondaryStatusCodes.AuthnFailed, "The user is not authenticated at the identity provider"); } Trace.Write("IdP", "Created SAML response"); return samlResponse; }
// Receive the SAML response from the identity provider. private void ReceiveSAMLResponse(out SAMLResponse samlResponse, out string relayState) { // Rather than separate endpoints per binding, we have a single endpoint and use a query string // parameter to determine the identity provider to service provider binding type. string bindingType = Request.QueryString[bindingQueryParameter]; Trace.Write("SP", "Receiving SAML response over binding " + bindingType); // Receive the SAML response over the specified binding. XmlElement samlResponseXml = null; switch (bindingType) { case BindingTypes.Post: ServiceProvider.ReceiveSAMLResponseByHTTPPost(Request, out samlResponseXml, out relayState); break; case BindingTypes.Artifact: // Receive the artifact. HTTPArtifact httpArtifact = null; ServiceProvider.ReceiveArtifactByHTTPArtifact(Request, false, out httpArtifact, out relayState); // Create an artifact resolve request. ArtifactResolve artifactResolve = new ArtifactResolve(); artifactResolve.Issuer = new Issuer(CreateAbsoluteURL("~/")); artifactResolve.Artifact = new Artifact(httpArtifact.ToString()); XmlElement artifactResolveXml = artifactResolve.ToXml(); // Send the artifact resolve request and receive the artifact response. XmlElement artifactResponseXml = ArtifactResolver.SendRequestReceiveResponse(Configuration.ArtifactResolutionServiceURL, artifactResolveXml); ArtifactResponse artifactResponse = new ArtifactResponse(artifactResponseXml); // Extract the authentication request from the artifact response. samlResponseXml = artifactResponse.SAMLMessage; break; default: throw new ArgumentException("Unknown binding type"); } // Verify the response's signature. if (SAMLMessageSignature.IsSigned(samlResponseXml)) { Trace.Write("SP", "Verifying response signature"); X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.IdPX509Certificate]; if (!SAMLMessageSignature.Verify(samlResponseXml, x509Certificate)) { throw new ArgumentException("The SAML response signature failed to verify."); } } // Deserialize the XML. samlResponse = new SAMLResponse(samlResponseXml); Trace.Write("SP", "Received SAML response"); }
public ComponentSpaceSaml2Response(XmlElement responseElement, string relayStateId, Saml2SsoBinding spBinding, X509Certificate2 encryptionCertificate, HttpContextBase httpContext) : base(responseElement, relayStateId, spBinding, encryptionCertificate, httpContext) { _samlResponse = new SAMLResponse(ResponseElement); SAML.HttpContext = HttpContext; }
// 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. SAMLAssertion samlAssertion = (SAMLAssertion)samlResponse.Assertions[0]; // Get the subject name identifier. string userName = samlAssertion.Subject.NameID.NameIdentifier; // Get the originally requested resource URL from the relay state. RelayState cachedRelayState = RelayStateCache.Remove(relayState); if (cachedRelayState == null) { Trace.Write("SP", "Nothing in cache"); return; } // 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"); }
// Create a SAML response with the user's local identity. private SAMLResponse CreateSAMLResponse() { Trace.Write("IdP", "Creating SAML response"); SAMLResponse samlResponse = new SAMLResponse(); samlResponse.Destination = Configuration.AssertionConsumerServiceURL; Issuer issuer = new Issuer(CreateAbsoluteURL("~/")); samlResponse.Issuer = issuer; samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null); SAMLAssertion samlAssertion = new SAMLAssertion(); samlAssertion.Issuer = issuer; Subject subject = new Subject(new NameID(User.Identity.Name)); SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer); SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData(); subjectConfirmationData.Recipient = Configuration.AssertionConsumerServiceURL; subjectConfirmation.SubjectConfirmationData = subjectConfirmationData; subject.SubjectConfirmations.Add(subjectConfirmation); samlAssertion.Subject = subject; AuthnStatement authnStatement = new AuthnStatement(); authnStatement.AuthnContext = new AuthnContext(); authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Password); samlAssertion.Statements.Add(authnStatement); samlResponse.Assertions.Add(samlAssertion); Trace.Write("IdP", "Created SAML response"); return samlResponse; }
private static string BuildResponseURL(string strResponse, string strPatientURL) { var sb = new StringBuilder(); var xml = new XmlDocument(); xml.LoadXml(Util.DecodeBase64(strResponse)); var samlResponse = new SAMLResponse(xml.DocumentElement); foreach (SAMLAssertion samlAssertion in samlResponse.Assertions) { foreach (var attributeStatement in samlAssertion.GetAttributeStatements()) { foreach (SAMLAttribute samlAttribute in attributeStatement.Attributes) { if (samlAttribute.Name != "idptoken") { continue; } sb.Append(strPatientURL); sb.Append("&idptoken="); sb.Append(samlAttribute.Values.FirstOrDefault()); } } } return(sb.ToString()); }
public void CheckOrDoLogin() { var respostaSaml = Request.Form[KEY_RESPONSE_SAML]; if (respostaSaml != null) { IsLoggedIn = true; var samlResponse = new SAMLResponse(); var xDoc = samlResponse.ParseSAMLResponse(respostaSaml); var certificado = GetCertificateData(URL_CERTIFICATE); if (samlResponse.IsResponseValid(xDoc, certificado)) { SamlUser = samlResponse.ParseSAMLAttribute(xDoc, USER_ATTRIBUTE); } else { throw new InvalidOperationException("Resposta SAML do IDP (Provedor de identidade não foi aceita."); } } else if (!IsLoggedIn) { var request = new SAMLRequest(); var url = string.Concat( LOGIN_URL, "?SAMLRequest=", HttpUtility.UrlEncode(request.GetSAMLRequest(Request.Url.ToString(), ENTITY_ID))); Response.Redirect(url); } }
protected void Page_Load(object sender, EventArgs e) { try { Trace.Write("IdP", "SSO service"); string targetURL = Request.QueryString[targetQueryParameter]; if (string.IsNullOrEmpty(targetURL)) { return; } Trace.Write("IdP", "Target URL: " + targetURL); // Create a SAML response with the user's local identity. SAMLResponse samlResponse = CreateSAMLResponse(); // Send the SAML response to the service provider. SendSAMLResponse(samlResponse, targetURL); } catch (Exception exception) { Trace.Write("IdP", "Error in SSO service", exception); } }
private string ParseSAMLResponse(string strResponse) { var strPatientURL = queryParameters.FirstOrDefault(i => i.Key == "patientUrl").Value; var sb = new StringBuilder(); var xml = new XmlDocument(); xml.LoadXml(Util.DecodeBase64(strResponse)); var samlResponse = new SAMLResponse(xml.DocumentElement); File.WriteAllText("SAMLResponse.xml", samlResponse.ToString()); foreach (SAMLAssertion samlAssertion in samlResponse.Assertions) { foreach (var attributeStatement in samlAssertion.GetAttributeStatements()) { foreach (SAMLAttribute samlAttribute in attributeStatement.Attributes) { if (samlAttribute.Name != "idptoken") { continue; } sb.Append(strPatientURL); sb.Append("&idptoken="); sb.Append(samlAttribute.Values.FirstOrDefault()); } } } return(sb.ToString()); }
internal SAMLResponse LoadURL(string URL) { UriBuilder URLBuild = new UriBuilder(URL); OrigURL = URLBuild.Uri; BrowserCtrl.Url = URLBuild.Uri; this.ShowDialog(); SAMLResponse response = new SAMLResponse(); try { SAMLDocument respdocument = new SAMLDocument(HTMLContent); response.Response = respdocument; } catch { response.ResponseCode = SAMLResponse.ExitType.Warning; } try { response.ResponseRaw = HTMLContent.Body.InnerHtml; response.ResponseCode = SAMLResponse.ExitType.Success; } catch (Exception ex) { response.ResponseCode = SAMLResponse.ExitType.Failed; } return(response); }
// Receive the SAML response from the identity provider. private void ReceiveSAMLResponse(out SAMLResponse samlResponse, out string relayState) { // Receive the SAML response over the specified binding. XmlElement samlResponseXml = null; ServiceProvider.ReceiveSAMLResponseByHTTPPost(Request, out samlResponseXml, out relayState); Session["SAML_XML"] = samlResponseXml.OuterXml; // Verify the response's signature. if (SAMLMessageSignature.IsSigned(samlResponseXml)) { //Verifying response signature X509Certificate2 x509Certificate = GetVendorCertificate(); if (!SAMLMessageSignature.Verify(samlResponseXml, x509Certificate)) { throw new ArgumentException("The SAML response signature failed to verify."); } } // Deserialize the XML. samlResponse = new SAMLResponse(samlResponseXml); }
// Receive the SAML response from the identity provider. private void ReceiveSAMLResponse(out SAMLResponse samlResponse, out string relayState) { Trace.Write("SP", "Receiving SAML response"); // Receive the SAML response. XmlElement samlResponseXml = null; ServiceProvider.ReceiveSAMLResponseByHTTPPost(Request, out samlResponseXml, out relayState); // Verify the response's signature. if (SAMLMessageSignature.IsSigned(samlResponseXml)) { Trace.Write("SP", "Verifying response signature"); X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.IdPX509Certificate]; if (!SAMLMessageSignature.Verify(samlResponseXml, x509Certificate)) { throw new ArgumentException("The SAML response signature failed to verify."); } } // Deserialize the XML. samlResponse = new SAMLResponse(samlResponseXml); Trace.Write("SP", "Received SAML response"); }
public ComponentSpaceSaml2Response(XmlElement responseElement, string relayStateId, Saml2SsoBinding spBinding, X509Certificate2 encryptionCertificate, HttpContextBase httpContext) : base(responseElement, relayStateId, spBinding, encryptionCertificate, httpContext) { _samlResponse = new SAMLResponse(ResponseElement); SAML.HttpContext = HttpContext; }
// Receive the SAML response from the identity provider. private void ReceiveSAMLResponse(ref SAMLResponse samlResponse, ref string relayState) { Trace.Write("SP", "Receiving SAML response"); // Determine the identity provider to service provider binding type. // We use a query string parameter rather than having separate endpoints per binding. string bindingType = Request.QueryString[bindingQueryParameter]; // Receive the SAML response over the specified binding. XmlElement samlResponseXml = null; switch (bindingType) { case SAMLIdentifiers.BindingURIs.HTTPPost: ServiceProvider.ReceiveSAMLResponseByHTTPPost(Request, out samlResponseXml, out relayState); break; case SAMLIdentifiers.BindingURIs.HTTPArtifact: // Receive the artifact. HTTPArtifact httpArtifact = null; ServiceProvider.ReceiveArtifactByHTTPArtifact(Request, false, out httpArtifact, out relayState); // Create an artifact resolve request. ArtifactResolve artifactResolve = new ArtifactResolve(); artifactResolve.Issuer = new Issuer(CreateAbsoluteURL("~/")); artifactResolve.Artifact = new Artifact(httpArtifact.ToString()); XmlElement artifactResolveXml = artifactResolve.ToXml(); // Send the artifact resolve request and receive the artifact response. string spArtifactResponderURL = WebConfigurationManager.AppSettings["idpArtifactResponderURL"]; XmlElement artifactResponseXml = ArtifactResolver.SendRequestReceiveResponse(spArtifactResponderURL, artifactResolveXml); ArtifactResponse artifactResponse = new ArtifactResponse(artifactResponseXml); // Extract the SAML response from the artifact response. samlResponseXml = artifactResponse.SAMLMessage; break; default: Trace.Write("SP", "Invalid identity provider to service provider binding"); return; } // Verify the response's signature. X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.IdPX509Certificate]; if (!SAMLMessageSignature.Verify(samlResponseXml, x509Certificate)) { throw new ArgumentException("The SAML response signature failed to verify."); } // Deserialize the XML. samlResponse = new SAMLResponse(samlResponseXml); Trace.Write("SP", "Received SAML response"); }
// 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.GetUnsignedAssertions().Count > 0) { samlAssertion = samlResponse.GetUnsignedAssertions()[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"); }
// Create a SAML response with the user's local identity. private SAMLResponse CreateSAMLResponse() { Trace.Write("IdP", "Creating SAML response"); SAMLResponse samlResponse = new SAMLResponse(); samlResponse.Destination = Configuration.AssertionConsumerServiceURL; Issuer issuer = new Issuer(Configuration.Issuer); samlResponse.Issuer = issuer; samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null); SAMLAssertion samlAssertion = new SAMLAssertion(); samlAssertion.Issuer = issuer; // For simplicity, a configured Salesforce user name is used. // NB. You must update the web.config to specify a valid Salesforce user name. // In a real world application you would perform some sort of local to Salesforce identity mapping. Subject subject = new Subject(new NameID(Configuration.SalesforceLoginID, null, null, SAMLIdentifiers.NameIdentifierFormats.Unspecified, null)); SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer); SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData(); subjectConfirmationData.Recipient = Configuration.AssertionConsumerServiceURL; subjectConfirmation.SubjectConfirmationData = subjectConfirmationData; subject.SubjectConfirmations.Add(subjectConfirmation); samlAssertion.Subject = subject; Conditions conditions = new Conditions(new TimeSpan(1, 0, 0)); AudienceRestriction audienceRestriction = new AudienceRestriction(); audienceRestriction.Audiences.Add(new Audience(audienceURI)); conditions.ConditionsList.Add(audienceRestriction); samlAssertion.Conditions = conditions; subjectConfirmationData.NotOnOrAfter = conditions.NotOnOrAfter; AuthnStatement authnStatement = new AuthnStatement(); authnStatement.AuthnContext = new AuthnContext(); authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Unspecified); samlAssertion.Statements.Add(authnStatement); AttributeStatement attributeStatement = new AttributeStatement(); attributeStatement.Attributes.Add(new SAMLAttribute(AttributeNames.SSOStartPage, SAMLIdentifiers.AttributeNameFormats.Unspecified, null, CreateAbsoluteURL("~/Login.aspx"))); attributeStatement.Attributes.Add(new SAMLAttribute(AttributeNames.LogoutURL, SAMLIdentifiers.AttributeNameFormats.Unspecified, null, CreateAbsoluteURL("~/Logout.aspx"))); samlAssertion.Statements.Add(attributeStatement); samlResponse.Assertions.Add(samlAssertion); Trace.Write("IdP", "Created SAML response"); return(samlResponse); }
protected void Page_Load(object sender, EventArgs e) { try { // Get the saved SSO state, if any. // If there isn't saved state then receive the authentication request. // If there is saved state then we've just completed a local login in response to a prior authentication request. SSOState ssoState = (SSOState)Session[ssoSessionKey]; if (ssoState == null) { Trace.Write("IdP", "SSO service"); // Receive the authentication request and relay state. AuthnRequest authnRequest = null; string relayState = null; ReceiveAuthnRequest(out authnRequest, out relayState); // Process the request. bool forceAuthn = authnRequest.ForceAuthn; ssoState = new SSOState(); ssoState.AuthnRequest = authnRequest; ssoState.RelayState = relayState; // Determine whether or not a local login is required. bool requireLocalLogin = IsLocalLoginRequired(forceAuthn); // If a local login is required then save the session state and initiate a local login. if (requireLocalLogin) { Session[ssoSessionKey] = ssoState; FormsAuthentication.RedirectToLoginPage(); return; } } // Create a SAML response with the user's local identity, if any. SAMLResponse samlResponse = CreateSAMLResponse(ssoState.AuthnRequest); // Send the SAML response to the service provider. SendSAMLResponse(samlResponse, ssoState.RelayState); // Clear the SSO state. Session[ssoSessionKey] = null; } catch (Exception exception) { Trace.Write("IdP", "Error in SSO service", exception); } }
// Create a SAML response with the user's local identity, if any, or indicating an error. private SAMLResponse CreateSAMLResponse(AuthnRequest authnRequest) { Trace.Write("IdP", "Creating SAML response"); SAMLResponse samlResponse = new SAMLResponse(); samlResponse.InResponseTo = authnRequest.ID; samlResponse.Destination = authnRequest.AssertionConsumerServiceURL; Issuer issuer = new Issuer(CreateAbsoluteURL("~/")); samlResponse.Issuer = issuer; if (User.Identity.IsAuthenticated) { samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null); SAMLAssertion samlAssertion = new SAMLAssertion(); samlAssertion.Issuer = issuer; samlAssertion.Conditions = new Conditions(new TimeSpan(0, 10, 0)); AudienceRestriction audienceRestriction = new AudienceRestriction(); audienceRestriction.Audiences.Add(new Audience(authnRequest.AssertionConsumerServiceURL)); samlAssertion.Conditions.ConditionsList.Add(audienceRestriction); Subject subject = new Subject(new NameID(User.Identity.Name)); SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer); SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData(); subjectConfirmationData.InResponseTo = authnRequest.ID; subjectConfirmationData.Recipient = authnRequest.AssertionConsumerServiceURL; subjectConfirmationData.NotBefore = samlAssertion.Conditions.NotBefore; subjectConfirmationData.NotOnOrAfter = samlAssertion.Conditions.NotOnOrAfter; subjectConfirmation.SubjectConfirmationData = subjectConfirmationData; subject.SubjectConfirmations.Add(subjectConfirmation); samlAssertion.Subject = subject; AuthnStatement authnStatement = new AuthnStatement(); authnStatement.AuthnContext = new AuthnContext(); authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Password); samlAssertion.Statements.Add(authnStatement); samlResponse.Assertions.Add(samlAssertion); } else { samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Responder, SAMLIdentifiers.SecondaryStatusCodes.AuthnFailed, "The user is not authenticated at the identity provider"); } Trace.Write("IdP", "Created SAML response"); return(samlResponse); }
/// <summary> /// This Post Action is used to Generate and POST the SAML Repsonse for and IDP initiated SSO /// </summary> public IActionResult OnPost(string Tenant, string Policy) { string b2cloginurl = _configuration["SAMLTEST:b2cloginurl"]; Policy = Policy.StartsWith("B2C_1A_") ? Policy : "B2C_1A_" + Policy; string ACS = "https://" + b2cloginurl + "/te/" + Tenant + ".onmicrosoft.com/" + Policy + "/samlp/sso/assertionconsumer"; SAMLResponse Resp = new SAMLResponse(ACS, "", SAMLHelper.GetThisURL(this), _configuration); string SAMLResponse = Convert.ToBase64String(Encoding.UTF8.GetBytes(Resp.ToString())); return(Content(SAMLHelper.GeneratePost(SAMLResponse, ACS), "text/html")); }
protected void Page_Load(object sender, EventArgs e) { SAMLResponse samlResponse = new SAMLResponse(); XmlDocument xDoc = samlResponse.ParseSAMLResponse(Request.Form["SAMLResponse"]); if (samlResponse.IsResponseValid(xDoc)) { Response.Write("SAML Response from IDP Was Accepted. Authenticated user is " + samlResponse.ParseSAMLNameID(xDoc)); } else { Response.Write("SAML Response from IDP Was Not Accepted"); } }
// Receive the SAML response from the identity provider. private void ReceiveSAMLResponse(out SAMLResponse samlResponse, out string relayState) { Trace.Write("SP", "Receiving SAML response."); // Receive the SAML response. XmlElement samlResponseXml = null; ServiceProvider.ReceiveSAMLResponseByHTTPPost(Request, out samlResponseXml, out relayState); // Deserialize the XML. samlResponse = new SAMLResponse(samlResponseXml); Trace.Write("SP", "Received SAML response"); }
// Process an error SAML response. private void ProcessErrorSAMLResponse(SAMLResponse samlResponse) { //"Processing error SAML response"); string errorMessage = null; if (samlResponse.Status.StatusMessage != null) { errorMessage = samlResponse.Status.StatusMessage.Message; } //Response.Redirect("~/Login.aspx", false); //"Processed error 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"); }
// 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"); }
// Create a SAML response with the user's local identity. private SAMLResponse CreateSAMLResponse() { Trace.Write("IdP", "Creating SAML response"); SAMLResponse samlResponse = new SAMLResponse(); samlResponse.Destination = Configuration.AssertionConsumerServiceURL; Issuer issuer = new Issuer(Configuration.Issuer); samlResponse.Issuer = issuer; samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null); SAMLAssertion samlAssertion = new SAMLAssertion(); samlAssertion.Issuer = issuer; // For simplicity, a configured Salesforce user name is used. // NB. You must update the web.config to specify a valid Salesforce user name. // In a real world application you would perform some sort of local to Salesforce identity mapping. Subject subject = new Subject(new NameID(Configuration.SalesforceLoginID, null, null, SAMLIdentifiers.NameIdentifierFormats.Unspecified, null)); SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer); SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData(); subjectConfirmationData.Recipient = Configuration.AssertionConsumerServiceURL; subjectConfirmation.SubjectConfirmationData = subjectConfirmationData; subject.SubjectConfirmations.Add(subjectConfirmation); samlAssertion.Subject = subject; Conditions conditions = new Conditions(new TimeSpan(1, 0, 0)); AudienceRestriction audienceRestriction = new AudienceRestriction(); audienceRestriction.Audiences.Add(new Audience(audienceURI)); conditions.ConditionsList.Add(audienceRestriction); samlAssertion.Conditions = conditions; subjectConfirmationData.NotOnOrAfter = conditions.NotOnOrAfter; AuthnStatement authnStatement = new AuthnStatement(); authnStatement.AuthnContext = new AuthnContext(); authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Unspecified); samlAssertion.Statements.Add(authnStatement); AttributeStatement attributeStatement = new AttributeStatement(); attributeStatement.Attributes.Add(new SAMLAttribute(AttributeNames.SSOStartPage, SAMLIdentifiers.AttributeNameFormats.Unspecified, null, CreateAbsoluteURL("~/Login.aspx"))); attributeStatement.Attributes.Add(new SAMLAttribute(AttributeNames.LogoutURL, SAMLIdentifiers.AttributeNameFormats.Unspecified, null, CreateAbsoluteURL("~/Logout.aspx"))); samlAssertion.Statements.Add(attributeStatement); samlResponse.Assertions.Add(samlAssertion); Trace.Write("IdP", "Created SAML response"); return samlResponse; }
// Send the SAML response to the SP. private void SendSAMLResponse(SAMLResponse samlResponse, string relayState) { Trace.Write("IdP", "Sending SAML response"); // Serialize the SAML response for transmission. XmlElement samlResponseXml = samlResponse.ToXml(); // Sign the SAML response. X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.IdPX509Certificate]; SAMLMessageSignature.Generate(samlResponseXml, x509Certificate.PrivateKey, x509Certificate); IdentityProvider.SendSAMLResponseByHTTPPost(Response, Configuration.AssertionConsumerServiceURL, samlResponseXml, relayState); Trace.Write("IdP", "Sent SAML response"); }
// Process an error SAML response. private void ProcessErrorSAMLResponse(SAMLResponse samlResponse) { Trace.Write("SP", "Processing error SAML response"); string errorMessage = null; if (samlResponse.Status.StatusMessage != null) { errorMessage = samlResponse.Status.StatusMessage.Message; } string redirectURL = String.Format("~/LoginChoice.aspx?{0}={1}", errorQueryParameter, HttpUtility.UrlEncode(errorMessage)); Response.Redirect(redirectURL, false); Trace.Write("SP", "Processed error SAML response"); }
// Create a SAML response with the user's local identity, if any, or indicating an error. private SAMLResponse CreateSAMLResponse(SSOState ssoState) { Trace.Write("IdP", "Creating SAML response"); SAMLResponse samlResponse = new SAMLResponse(); string issuerURL = CreateAbsoluteURL("~/"); Issuer issuer = new Issuer(issuerURL); samlResponse.Issuer = issuer; if (User.Identity.IsAuthenticated) { samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null); SAMLAssertion samlAssertion = new SAMLAssertion(); samlAssertion.Issuer = issuer; Subject subject = new Subject(new NameID(User.Identity.Name)); SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer); SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData(); subjectConfirmationData.InResponseTo = ssoState.authnRequest.ID; subjectConfirmationData.Recipient = ssoState.assertionConsumerServiceURL; subjectConfirmation.SubjectConfirmationData = subjectConfirmationData; subject.SubjectConfirmations.Add(subjectConfirmation); samlAssertion.Subject = subject; AuthnStatement authnStatement = new AuthnStatement(); authnStatement.AuthnContext = new AuthnContext(); authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Password); samlAssertion.Statements.Add(authnStatement); // Attributes may be included in the SAML assertion. AttributeStatement attributeStatement = new AttributeStatement(); attributeStatement.Attributes.Add(new SAMLAttribute("Membership", SAMLIdentifiers.AttributeNameFormats.Basic, null, "Gold")); samlAssertion.Statements.Add(attributeStatement); samlResponse.Assertions.Add(samlAssertion); } else { samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Responder, SAMLIdentifiers.SecondaryStatusCodes.AuthnFailed, "The user is not authenticated at the identity provider"); } Trace.Write("IdP", "Created SAML response"); return(samlResponse); }
// Process an error SAML response. private void ProcessErrorSAMLResponse(SAMLResponse samlResponse) { Trace.Write("SP", "Processing error SAML response"); string errorMessage = null; if (samlResponse.Status.StatusMessage != null) { errorMessage = samlResponse.Status.StatusMessage.Message; } string redirectURL = String.Format("~/LoginChoice.aspx?{0}={1}", errorQueryParameter, HttpUtility.UrlEncode(errorMessage)); Response.Redirect(redirectURL, false); Trace.Write("SP", "Processed error SAML response"); }
// Process the SAML response returned by the identity provider in response // to the authentication request sent by the service provider. private void ProcessSAMLResponse() { // Receive the SAML response. SAMLResponse samlResponse = null; string relayState = null; ReceiveSAMLResponse(out samlResponse, out relayState); // Check whether the SAML response indicates success or an error and process accordingly. if (samlResponse.IsSuccess()) { ProcessSuccessSAMLResponse(samlResponse, relayState); } else { ProcessErrorSAMLResponse(samlResponse); } }
protected void Page_Load(object sender, EventArgs e) { try { Trace.Write("SP", "Assertion consumer service"); // Receive the SAML response. SAMLResponse samlResponse = null; string relayState = null; ReceiveSAMLResponse(out samlResponse, out relayState); // Process the SAML response. ProcessSAMLResponse(samlResponse, relayState); } catch (Exception exception) { Trace.Write("SP", "Error in assertion consumer service", exception); } }
// Send the SAML response over the specified binding. private void SendSAMLResponse(SAMLResponse samlResponse, SSOState ssoState) { Trace.Write("IdP", "Sending SAML response"); // Serialize the SAML response for transmission. XmlElement samlResponseXml = samlResponse.ToXml(); // Sign the SAML response X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.IdPX509Certificate]; SAMLMessageSignature.Generate(samlResponseXml, x509Certificate.PrivateKey, x509Certificate); // Send the SAML response to the service provider. switch (ssoState.idpProtocolBinding) { case SAMLIdentifiers.Binding.HTTPPost: IdentityProvider.SendSAMLResponseByHTTPPost(Response, ssoState.assertionConsumerServiceURL, samlResponseXml, ssoState.relayState); break; case SAMLIdentifiers.Binding.HTTPArtifact: // Create the artifact. string identificationURL = CreateAbsoluteURL("~/"); HTTPArtifactType4 httpArtifact = new HTTPArtifactType4(HTTPArtifactType4.CreateSourceId(identificationURL), HTTPArtifactType4.CreateMessageHandle()); // Cache the authentication request for subsequent sending using the artifact resolution protocol. HTTPArtifactState httpArtifactState = new HTTPArtifactState(samlResponseXml, null); HTTPArtifactStateCache.Add(httpArtifact, httpArtifactState); // Send the artifact. IdentityProvider.SendArtifactByHTTPArtifact(Response, ssoState.assertionConsumerServiceURL, httpArtifact, ssoState.relayState, false); break; default: Trace.Write("IdP", "Invalid identity provider binding"); break; } Trace.Write("IdP", "Sent SAML response"); }
/// <summary> /// This Get Action is used to Generate and POST the SAML Repsonse /// based on a supplied AuthN Request /// </summary> public void OnGet(String SAMLRequest, String RelayState) { this.RelayState = RelayState; String sml = SAMLHelper.Decompress(SAMLRequest); XmlDocument doc = new XmlDocument(); XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion"); nsmgr.AddNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol"); doc.LoadXml(sml); XmlElement root = doc.DocumentElement; ACS = root.SelectSingleNode("/samlp:AuthnRequest/@AssertionConsumerServiceURL", nsmgr).Value; ID = root.SelectSingleNode("/samlp:AuthnRequest/@ID", nsmgr).Value; string httpors = HttpContext.Request.IsHttps ? "https://" : "http://"; string thisurl = httpors + HttpContext.Request.Host.Value; SAMLResponse Resp = new SAMLResponse(ACS, ID, thisurl, _configuration); this.SAMLResponse = Convert.ToBase64String(Encoding.UTF8.GetBytes(Resp.ToString())); this.RelayState = RelayState; }
// Create a SAML response with the user's local identity. private SAMLResponse CreateSAMLResponse() { Trace.Write("IdP", "Creating SAML response"); SAMLResponse samlResponse = new SAMLResponse(); samlResponse.Destination = Configuration.AssertionConsumerServiceURL; Issuer issuer = new Issuer(CreateAbsoluteURL("~/")); samlResponse.Issuer = issuer; samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null); SAMLAssertion samlAssertion = new SAMLAssertion(); samlAssertion.Issuer = issuer; Subject subject = new Subject(new NameID(User.Identity.Name)); SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer); SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData(); subjectConfirmationData.Recipient = Configuration.AssertionConsumerServiceURL; subjectConfirmation.SubjectConfirmationData = subjectConfirmationData; subject.SubjectConfirmations.Add(subjectConfirmation); samlAssertion.Subject = subject; AuthnStatement authnStatement = new AuthnStatement(); authnStatement.AuthnContext = new AuthnContext(); authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Password); samlAssertion.Statements.Add(authnStatement); samlResponse.Assertions.Add(samlAssertion); Trace.Write("IdP", "Created SAML response"); return(samlResponse); }
public SAMLResponse ProcessSamlLoginResponse(string b64response) { try { byte[] reqDataB64 = Convert.FromBase64String(b64response); string reqData = Encoding.UTF8.GetString(reqDataB64); XmlDocument xml = new XmlDocument(); xml.PreserveWhitespace = true; xml.LoadXml(reqData); _logger.Trace("Respuesta de cl@ve: {0}", xml.InnerXml); SAMLEngine.Instance.Init(); SAMLResponse sr = SAMLEngine.Instance.HandleResponse(xml); return sr; } catch (Exception e) { _logger.Error(e); SAMLResponse sr = new SAMLResponse(); sr.ErrorCode = -11; sr.StatusCode = SAMLConstants.StatusCode.AUTHN_FAILED; sr.StatusMessage = e.Message; return sr; } }
public AWSCredentials GetCredential(string IdentityURL, string RoleARN, string ProviderARN) { Browser ADFSBrowser = new Browser(); SAMLResponse res = ADFSBrowser.LoadURL(IdentityURL); string[] role = new string[] { ProviderARN, RoleARN }; ImmutableCredentials creds; AWSCredentials AWSCreds = new AWSCredentials(); switch (res.ResponseCode) { case SAMLResponse.ExitType.Success: creds = GetSamlRoleCredentails(res.Response.SessionValue, role).GetCredentials(); AWSCreds.AccessKeyID = creds.AccessKey; AWSCreds.SecretAccessKey = creds.SecretKey; AWSCreds.SessionToken = creds.Token; break; case SAMLResponse.ExitType.Warning: throw new System.Exception("SAML generation failed because the SAML data was only partially recieved. Check you have the correct permissions to the ARN roles"); break; case SAMLResponse.ExitType.Failed: throw new System.Exception("SAML generation failed because no SAML data was recieved. Check the Identity URL is correct and reachable."); break; } return(AWSCreds); }
// Send the SAML response over the specified binding. private void SendSAMLResponse(SAMLResponse samlResponse, SSOState ssoState) { Trace.Write("IdP", "Sending SAML response"); // Serialize the SAML response for transmission. XmlElement samlResponseXml = samlResponse.ToXml(); // Sign the SAML response X509Certificate2 x509Certificate = (X509Certificate2) Application[Global.IdPX509Certificate]; SAMLMessageSignature.Generate(samlResponseXml, x509Certificate.PrivateKey, x509Certificate); // Send the SAML response to the service provider. switch (ssoState.idpProtocolBinding) { case SAMLIdentifiers.Binding.HTTPPost: IdentityProvider.SendSAMLResponseByHTTPPost(Response, ssoState.assertionConsumerServiceURL, samlResponseXml, ssoState.relayState); break; case SAMLIdentifiers.Binding.HTTPArtifact: // Create the artifact. string identificationURL = CreateAbsoluteURL("~/"); HTTPArtifactType4 httpArtifact = new HTTPArtifactType4(HTTPArtifactType4.CreateSourceId(identificationURL), HTTPArtifactType4.CreateMessageHandle()); // Cache the authentication request for subsequent sending using the artifact resolution protocol. HTTPArtifactState httpArtifactState = new HTTPArtifactState(samlResponseXml, null); HTTPArtifactStateCache.Add(httpArtifact, httpArtifactState); // Send the artifact. IdentityProvider.SendArtifactByHTTPArtifact(Response, ssoState.assertionConsumerServiceURL, httpArtifact, ssoState.relayState, false); break; default: Trace.Write("IdP", "Invalid identity provider binding"); break; } Trace.Write("IdP", "Sent 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"); }
// Send the SAML response to the SP. private void SendSAMLResponse(SAMLResponse samlResponse, string relayState, string samlService) { Trace.Write("IdP", "Sending SAML response"); // Serialize the SAML response for transmission. XmlElement samlResponseXml = samlResponse.ToXml(); // Sign the SAML response. X509Certificate2 x509Certificate = (X509Certificate2)HttpContext.Application[FB.StrawPortal.MvcApplication.IdPX509Certificate]; SAMLMessageSignature.Generate(samlResponseXml, x509Certificate.PrivateKey, x509Certificate); //IdentityProvider.SendSAMLResponseByHTTPPost(Response, WebConfigurationManager.AppSettings["AssertionConsumerServiceURL"], samlResponseXml, relayState); ComponentSpace.SAML2.Bindings.HTTPPostBinding.SendResponse(Response.OutputStream, samlService, samlResponseXml, relayState); Trace.Write("IdP", "Sent SAML response"); }
// Receive the SAML response from the identity provider. private void ReceiveSAMLResponse(out SAMLResponse samlResponse, out string relayState) { Trace.Write("SP", "Receiving SAML response"); // Receive the SAML response. XmlElement samlResponseXml = null; var theRequest = (HttpRequest)HttpContext.GetService(typeof(HttpRequest)); ServiceProvider.ReceiveSAMLResponseByHTTPPost(theRequest, out samlResponseXml, out relayState); // Verify the response's signature. if (SAMLMessageSignature.IsSigned(samlResponseXml)) { Trace.Write("SP", "Verifying response signature"); X509Certificate2 x509Certificate = (X509Certificate2)HttpContext.Application[MvcApplication.EncrypterX509Certificate]; if (!SAMLMessageSignature.Verify(samlResponseXml, x509Certificate)) { throw new ArgumentException("The SAML response signature failed to verify."); } } else { throw new ArgumentException("The SAML response signature failed to verify."); } // Deserialize the XML. samlResponse = new SAMLResponse(samlResponseXml); Trace.Write("SP", "Received SAML response"); }
// Send the SAML response to the SP. private void SendSAMLResponse(SAMLResponse samlResponse, string relayState) { Trace.Write("IdP", "Sending SAML response"); // Serialize the SAML response for transmission. XmlElement samlResponseXml = samlResponse.ToXml(); // Sign the SAML response. X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.IdPX509Certificate]; SAMLMessageSignature.Generate(samlResponseXml, x509Certificate.PrivateKey, x509Certificate); IdentityProvider.SendSAMLResponseByHTTPPost(Response, Configuration.AssertionConsumerServiceURL, samlResponseXml, relayState); Trace.Write("IdP", "Sent SAML response"); }
// Receive the SAML response from the identity provider. private void ReceiveSAMLResponse(out SAMLResponse samlResponse, out string relayState) { // Rather than separate endpoints per binding, we have a single endpoint and use a query string // parameter to determine the identity provider to service provider binding type. string bindingType = Request.QueryString[bindingQueryParameter]; Trace.Write("SP", "Receiving SAML response over binding " + bindingType); // Receive the SAML response over the specified binding. XmlElement samlResponseXml = null; switch (bindingType) { case BindingTypes.Post: ServiceProvider.ReceiveSAMLResponseByHTTPPost(Request, out samlResponseXml, out relayState); break; case BindingTypes.Artifact: // Receive the artifact. HTTPArtifact httpArtifact = null; ServiceProvider.ReceiveArtifactByHTTPArtifact(Request, false, out httpArtifact, out relayState); // Create an artifact resolve request. ArtifactResolve artifactResolve = new ArtifactResolve(); artifactResolve.Issuer = new Issuer(CreateAbsoluteURL("~/")); artifactResolve.Artifact = new Artifact(httpArtifact.ToString()); XmlElement artifactResolveXml = artifactResolve.ToXml(); // Send the artifact resolve request and receive the artifact response. XmlElement artifactResponseXml = ArtifactResolver.SendRequestReceiveResponse(Configuration.ArtifactResolutionServiceURL, artifactResolveXml); ArtifactResponse artifactResponse = new ArtifactResponse(artifactResponseXml); // Extract the authentication request from the artifact response. samlResponseXml = artifactResponse.SAMLMessage; break; default: throw new ArgumentException("Unknown binding type"); } // Verify the response's signature. if (SAMLMessageSignature.IsSigned(samlResponseXml)) { Trace.Write("SP", "Verifying response signature"); X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.IdPX509Certificate]; if (!SAMLMessageSignature.Verify(samlResponseXml, x509Certificate)) { throw new ArgumentException("The SAML response signature failed to verify."); } } // Deserialize the XML. samlResponse = new SAMLResponse(samlResponseXml); Trace.Write("SP", "Received SAML response"); }
// Receive the SAML response from the identity provider. private void ReceiveSAMLResponse(out SAMLResponse samlResponse, out string relayState) { Trace.Write("SP", "Receiving SAML response."); // Receive the SAML response. XmlElement samlResponseXml = null; ServiceProvider.ReceiveSAMLResponseByHTTPPost(Request, out samlResponseXml, out relayState); // Deserialize the XML. samlResponse = new SAMLResponse(samlResponseXml); Trace.Write("SP", "Received SAML response"); }
// 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"); }
private void RedirectWithSAML(string dest) { var FBReturnToken = Session["FBReturnToken"].ToString(); SAMLResponse samlResponse = new SAMLResponse(); samlResponse.Destination = WebConfigurationManager.AppSettings["AssertionConsumerServiceURL"]; Issuer issuer = new Issuer( new Uri(Request.Url, Url.Content("~")).ToString()); samlResponse.Issuer = issuer; samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null); samlResponse.Assertions.Add(new SAMLAssertion(FBReturnToken)); var samlResponseXml = samlResponse.ToXml(); // Sign the SAML response. X509Certificate2 x509Certificate = (X509Certificate2)HttpContext.Application[MvcApplication.DecrypterX509Certificate]; SAMLMessageSignature.Generate(samlResponseXml, x509Certificate.PrivateKey, x509Certificate); HttpResponse theResponse = (HttpResponse)HttpContext.GetService(typeof(HttpResponse)); IdentityProvider.SendSAMLResponseByHTTPPost(theResponse, WebConfigurationManager.AppSettings["AssertionConsumerServiceURL"], samlResponseXml, dest); }
// Create a SAML response with the user's local identity, if any, or indicating an error. private SAMLResponse CreateSAMLResponse(AuthnRequest authnRequest) { Trace.Write("IdP", "Creating SAML response"); SAMLResponse samlResponse = new SAMLResponse(); samlResponse.Destination = Configuration.AssertionConsumerServiceURL; Issuer issuer = new Issuer(CreateAbsoluteURL("~/")); samlResponse.Issuer = issuer; if (User.Identity.IsAuthenticated) { samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null); SAMLAssertion samlAssertion = new SAMLAssertion(); samlAssertion.Issuer = issuer; Subject subject = new Subject(new NameID(User.Identity.Name)); SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer); SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData(); subjectConfirmationData.InResponseTo = authnRequest.ID; subjectConfirmationData.Recipient = Configuration.AssertionConsumerServiceURL; subjectConfirmation.SubjectConfirmationData = subjectConfirmationData; subject.SubjectConfirmations.Add(subjectConfirmation); samlAssertion.Subject = subject; AuthnStatement authnStatement = new AuthnStatement(); authnStatement.AuthnContext = new AuthnContext(); authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Password); samlAssertion.Statements.Add(authnStatement); samlResponse.Assertions.Add(samlAssertion); } else { samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Responder, SAMLIdentifiers.SecondaryStatusCodes.AuthnFailed, "The user is not authenticated at the identity provider"); } Trace.Write("IdP", "Created SAML response"); return samlResponse; }
// Receive the SAML response from the identity provider. private void ReceiveSAMLResponse(out SAMLResponse samlResponse, out string relayState) { Trace.Write("SP", "Receiving SAML response"); // Receive the SAML response. XmlElement samlResponseXml = null; ServiceProvider.ReceiveSAMLResponseByHTTPPost(Request, out samlResponseXml, out relayState); // Verify the response's signature. if (SAMLMessageSignature.IsSigned(samlResponseXml)) { Trace.Write("SP", "Verifying response signature"); X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.IdPX509Certificate]; if (!SAMLMessageSignature.Verify(samlResponseXml, x509Certificate)) { throw new ArgumentException("The SAML response signature failed to verify."); } } // Deserialize the XML. samlResponse = new SAMLResponse(samlResponseXml); Trace.Write("SP", "Received SAML response"); }