// 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; }
/// <summary> /// Merges the modified attributes into <code>AttributeStatement</code> of the assertion. /// </summary> private void InsertAttributes() { if (_assertionAttributes == null) { return; } // Generate the new AttributeStatement var attributeStatement = new AttributeStatement(); var statements = new List <object>(_encryptedAssertionAttributes.Count + _assertionAttributes.Count); statements.AddRange(_assertionAttributes.ToArray()); statements.AddRange(_encryptedAssertionAttributes.ToArray()); attributeStatement.Items = statements.ToArray(); var list = XmlAssertion.GetElementsByTagName(AttributeStatement.ElementName, Saml20Constants.Assertion); if (list.Count > 0) { // Remove the old AttributeStatement. XmlAssertion.RemoveChild(list[0]); // FIX _samlAssertion.DocumentElement.RemoveChild(list[0]); } // Only insert a new AttributeStatement if there are attributes. if (statements.Count > 0) { // Convert the new AttributeStatement to the Document Object Model and make a silent prayer that one day we will // be able to make this transition in a more elegant way. var attributeStatementDoc = Serialization.Serialize(attributeStatement); var attr = XmlAssertion.OwnerDocument.ImportNode(attributeStatementDoc.DocumentElement, true); // Insert the new statement. XmlAssertion.AppendChild(attr); } _encryptedAssertionAttributes = null; _assertionAttributes = null; }
private static void AddGeneralStatements(ref List <Statement> statements) { // Graph orientation: left to right var generalStyleSettings = new Dictionary <Id, Id>(); generalStyleSettings.Add(new Id("rankdir"), new Id("LR")); var generalStyleAttributes = new AttributeStatement(AttributeKinds.Graph, generalStyleSettings.ToImmutableDictionary()); statements.Add(generalStyleAttributes); // We draw filled rectangles var generalNodeStyleSettings = new Dictionary <Id, Id>(); generalNodeStyleSettings.Add(new Id("shape"), new Id("record")); generalNodeStyleSettings.Add(new Id("style"), new Id("filled")); generalNodeStyleSettings.Add(new Id("fontsize"), new Id("11")); generalNodeStyleSettings.Add(new Id("color"), new Id("gray75")); //generalNodeStyleSettings.Add(new Id("fontname"), new Id("Monospace")); var generalNodeStyleAttributes = new AttributeStatement(AttributeKinds.Node, generalNodeStyleSettings.ToImmutableDictionary()); statements.Add(generalNodeStyleAttributes); }
/// <summary> /// Extracts the list of attributes from the <AttributeStatement> of the assertion, and /// stores it in <code>_assertionAttributes</code>. /// </summary> private void ExtractAttributes() { _assertionAttributes = new List <SamlAttribute>(0); _encryptedAssertionAttributes = new List <EncryptedElement>(0); XmlNodeList list = _samlAssertion.GetElementsByTagName(AttributeStatement.ELEMENT_NAME, Saml20Constants.ASSERTION); if (list.Count == 0) { return; } // NOTE It would be nice to implement a better-performing solution where only the AttributeStatement is converted. // NOTE Namespace issues in the xml-schema "type"-attribute prevents this, though. Assertion assertion = Serialization.Deserialize <Assertion>(new XmlNodeReader(_samlAssertion)); List <AttributeStatement> attributeStatements = assertion.GetAttributeStatements(); if (attributeStatements.Count == 0 || attributeStatements[0].Items == null) { return; } AttributeStatement attributeStatement = attributeStatements[0]; foreach (object item in attributeStatement.Items) { if (item is SamlAttribute) { _assertionAttributes.Add((SamlAttribute)item); } if (item is EncryptedElement) { _encryptedAssertionAttributes.Add((EncryptedElement)item); } } }
public void AttributeStatement_Element() { Predicate <StatementAbstract> findAttributeStatement = delegate(StatementAbstract stmnt) { return(stmnt is AttributeStatement); }; Assertion saml20Assertion = AssertionUtil.GetBasicAssertion(); AttributeStatement attributeStatement = (AttributeStatement)Array.Find(saml20Assertion.Items, findAttributeStatement); // Add an encrypted attribute. EncryptedElement encAtt = new EncryptedElement(); encAtt.encryptedData = new EncryptedData(); encAtt.encryptedData.CipherData = new CipherData(); encAtt.encryptedData.CipherData.Item = string.Empty; encAtt.encryptedKey = new EncryptedKey[0]; attributeStatement.Items = new object[] { encAtt }; TestAssertion(saml20Assertion, "The DK-SAML 2.0 profile does not allow encrypted attributes."); // Add an attribute with the wrong nameformat. // Attribute att = DKSaml20EmailAttribute.create("*****@*****.**"); // att.NameFormat = "http://example.com"; // attributeStatement.Items = new object[] { att }; // testAssertion(saml20Assertion, "The DK-SAML 2.0 profile requires that an attribute's \"NameFormat\" element is urn:oasis:names:tc:SAML:2.0:attrname-format:uri."); // Clear all the attributes. attributeStatement.Items = new object[0]; TestAssertion(saml20Assertion, "AttributeStatement MUST contain at least one Attribute or EncryptedAttribute"); // Remove it. saml20Assertion = AssertionUtil.GetBasicAssertion(); List <StatementAbstract> statements = new List <StatementAbstract>(saml20Assertion.Items); statements.RemoveAll(findAttributeStatement); saml20Assertion.Items = statements.ToArray(); TestAssertion(saml20Assertion, "The DK-SAML 2.0 profile requires exactly one \"AuthnStatement\" element and one \"AttributeStatement\" element."); }
static void Main(string[] args) { Assertion _assertion = new Assertion(); // Here we create some SAML assertion with ID and Issuer name. Assertion assertion = new Assertion(); assertion.Id = "AssertionID"; assertion.Issuer.Value = "ISSUER"; // Create some SAML subject. Subject samlSubject = new Subject(); samlSubject.Items = new object[] { "My Subject" }; // // Create one SAML attribute with few values. List <SamlAttribute> attr = new List <SamlAttribute>(); attr.Name = "http://daenet.eu/saml"; attr.AttributeValue = new string[] { "Some Value 1" }; //attr.AttributeValues.Add("Some Value 2"); attr.Name = "My ATTR Value"; // // Now create the SAML statement containing one attribute and one subject. AttributeStatement samlAttributeStatement = new AttributeStatement(); samlAttributeStatement.Items = attr; samlAttributeStatement.SamlSubject = samlSubject; // Append the statement to the SAML assertion. assertion.Statements.Add(samlAttributeStatement); //return assertion return(assertion); }
/// <summary> /// Assembles our basic test assertion /// </summary> /// <returns>The <see cref="Assertion"/>.</returns> public static Assertion GetBasicAssertion() { var assertion = new Assertion { Issuer = new NameId(), Id = "_b8977dc86cda41493fba68b32ae9291d", IssueInstant = DateTime.UtcNow, Version = "2.0" }; assertion.Issuer.Value = GetBasicIssuer(); assertion.Subject = new Subject(); var subjectConfirmation = new SubjectConfirmation { Method = SubjectConfirmation.BearerMethod, SubjectConfirmationData = new SubjectConfirmationData { NotOnOrAfter = new DateTime(2008, 12, 31, 12, 0, 0, 0), Recipient = "http://borger.dk" } }; assertion.Subject.Items = new object[] { subjectConfirmation }; assertion.Conditions = new Conditions { NotOnOrAfter = new DateTime(2008, 12, 31, 12, 0, 0, 0) }; var audienceRestriction = new AudienceRestriction { Audience = GetAudiences().Select(u => u.ToString()).ToList() }; assertion.Conditions.Items = new List <ConditionAbstract>(new ConditionAbstract[] { audienceRestriction }); AuthnStatement authnStatement; { authnStatement = new AuthnStatement(); assertion.Items = new StatementAbstract[] { authnStatement }; authnStatement.AuthnInstant = new DateTime(2008, 1, 8); authnStatement.SessionIndex = "70225885"; authnStatement.AuthnContext = new AuthnContext { Items = new object[] { "urn:oasis:names:tc:SAML:2.0:ac:classes:X509", "http://www.safewhere.net/authncontext/declref" }, ItemsElementName = new[] { AuthnContextType.AuthnContextClassRef, AuthnContextType.AuthnContextDeclRef } }; } AttributeStatement attributeStatement; { attributeStatement = new AttributeStatement(); var surName = new SamlAttribute { FriendlyName = "SurName", Name = "urn:oid:2.5.4.4", NameFormat = SamlAttribute.NameformatUri, AttributeValue = new[] { "Fry" } }; var commonName = new SamlAttribute { FriendlyName = "CommonName", Name = "urn:oid:2.5.4.3", NameFormat = SamlAttribute.NameformatUri, AttributeValue = new[] { "Philip J. Fry" } }; var userName = new SamlAttribute { Name = "urn:oid:0.9.2342.19200300.100.1.1", NameFormat = SamlAttribute.NameformatUri, AttributeValue = new[] { "fry" } }; var email = new SamlAttribute { FriendlyName = "Email", Name = "urn:oid:0.9.2342.19200300.100.1.3", NameFormat = SamlAttribute.NameformatUri, AttributeValue = new[] { "*****@*****.**" } }; attributeStatement.Items = new object[] { surName, commonName, userName, email }; } assertion.Items = new StatementAbstract[] { authnStatement, attributeStatement }; return(assertion); }
private Assertion CreateAssertion(User user, string receiver, string nameIdFormat) { Assertion assertion = new Assertion(); { // Subject element assertion.Subject = new Subject(); assertion.ID = "id" + Guid.NewGuid().ToString("N"); assertion.IssueInstant = DateTime.Now.AddMinutes(10); assertion.Issuer = new NameID(); assertion.Issuer.Value = IDPConfig.ServerBaseUrl; SubjectConfirmation subjectConfirmation = new SubjectConfirmation(); subjectConfirmation.Method = SubjectConfirmation.BEARER_METHOD; subjectConfirmation.SubjectConfirmationData = new SubjectConfirmationData(); subjectConfirmation.SubjectConfirmationData.NotOnOrAfter = DateTime.Now.AddHours(1); subjectConfirmation.SubjectConfirmationData.Recipient = receiver; NameID nameId = new NameID(); nameId.Format = nameIdFormat; if (nameIdFormat == Saml20Constants.NameIdentifierFormats.Transient) { nameId.Value = $"https://data.gov.dk/model/core/eid/{user.Profile}/uuid/" + Guid.NewGuid(); } else { nameId.Value = $"https://data.gov.dk/model/core/eid/{user.Profile}/uuid/{user.uuid}"; } assertion.Subject.Items = new object[] { nameId, subjectConfirmation }; } { // Conditions element assertion.Conditions = new Conditions(); assertion.Conditions.Items = new List <ConditionAbstract>(); assertion.Conditions.NotOnOrAfter = DateTime.Now.AddHours(1); AudienceRestriction audienceRestriction = new AudienceRestriction(); audienceRestriction.Audience = new List <string>(); audienceRestriction.Audience.Add(receiver); assertion.Conditions.Items.Add(audienceRestriction); } List <StatementAbstract> statements = new List <StatementAbstract>(2); { // AuthnStatement element AuthnStatement authnStatement = new AuthnStatement(); authnStatement.AuthnInstant = DateTime.Now; authnStatement.SessionIndex = Convert.ToString(new Random().Next()); authnStatement.AuthnContext = new AuthnContext(); authnStatement.AuthnContext.Items = new object[] { "urn:oasis:names:tc:SAML:2.0:ac:classes:X509" }; // Wow! Setting the AuthnContext is .... verbose. authnStatement.AuthnContext.ItemsElementName = new ItemsChoiceType5[] { ItemsChoiceType5.AuthnContextClassRef }; statements.Add(authnStatement); } { // Generate attribute list. AttributeStatement attributeStatement = new AttributeStatement(); List <SamlAttribute> attributes = new List <SamlAttribute>(user.Attributes.Count); foreach (KeyValuePair <string, string> att in user.Attributes) { var existingAttribute = attributes.FirstOrDefault(x => x.Name == att.Key); if (existingAttribute != null) { var attributesValues = new List <string>(); attributesValues.AddRange(existingAttribute.AttributeValue); attributesValues.Add(att.Value); existingAttribute.AttributeValue = attributesValues.ToArray(); } else { SamlAttribute attribute = new SamlAttribute(); attribute.Name = att.Key; attribute.AttributeValue = new string[] { att.Value }; attribute.NameFormat = SamlAttribute.NAMEFORMAT_URI; attributes.Add(attribute); } } attributeStatement.Items = attributes.ToArray(); statements.Add(attributeStatement); } assertion.Items = statements.ToArray(); return(assertion); }
private static XmlElement CreateSamlResponse(string assertionConsumerServiceUrl, List <SAMLAttribute> attributes, string requestId = null, bool signAssertion = false, bool signResponse = false, bool encryptAssertion = false) { var samlResponse = new SAMLResponse { Destination = assertionConsumerServiceUrl }; var issuer = new Issuer(SAMLConfiguration.Current.IdentityProviderConfiguration.Name); var issuerX509CertificateFilePath = Path.Combine(HttpRuntime.AppDomainAppPath, SAMLConfiguration.Current.IdentityProviderConfiguration.CertificateFile); var issuerX509Certificate = new X509Certificate2(issuerX509CertificateFilePath, SAMLConfiguration.Current.IdentityProviderConfiguration.CertificatePassword); var partner = SessionHelper.Get <string>(PartnerSpSessionKey) ?? SAMLConfiguration.Current.ServiceProviderConfiguration.Name; var partnerConfig = SAMLConfiguration.Current.PartnerServiceProviderConfigurations[partner]; var partnerX509CertificateFilePath = string.Empty; var partnerX509Certificate = null as X509Certificate2; if (partnerConfig != null) { partnerX509CertificateFilePath = Path.Combine(HttpRuntime.AppDomainAppPath, partnerConfig.CertificateFile); partnerX509Certificate = new X509Certificate2(partnerX509CertificateFilePath); signAssertion = partnerConfig.SignAssertion; signResponse = partnerConfig.SignSAMLResponse; encryptAssertion = partnerConfig.EncryptAssertion; } samlResponse.Issuer = issuer; samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null); samlResponse.IssueInstant = DateTime.Now; samlResponse.InResponseTo = requestId; var samlAssertion = new SAMLAssertion { Issuer = issuer, IssueInstant = samlResponse.IssueInstant }; var profileId = attributes.Where(a => a.Name == PortalClaimTypes.ProfileId).Select(a => a.Values[0].ToString()).FirstOrDefault(); var subject = new Subject(new NameID(profileId)); var subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer); var subjectConfirmationData = new SubjectConfirmationData { Recipient = assertionConsumerServiceUrl }; subjectConfirmation.SubjectConfirmationData = subjectConfirmationData; subject.SubjectConfirmations.Add(subjectConfirmation); samlAssertion.Subject = subject; var conditions = new Conditions(DateTime.Now, DateTime.Now.AddDays(1)); var audienceRestriction = new AudienceRestriction(); audienceRestriction.Audiences.Add(new Audience(partner)); conditions.ConditionsList.Add(audienceRestriction); samlAssertion.Conditions = conditions; var authnStatement = new AuthnStatement { AuthnContext = new AuthnContext(), AuthnInstant = samlResponse.IssueInstant }; authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.X509); samlAssertion.Statements.Add(authnStatement); attributes.ForEach(a => { var attributeStatement = new AttributeStatement(); attributeStatement.Attributes.Add(a); samlAssertion.Statements.Add(attributeStatement); }); var samlAssertionXml = samlAssertion.ToXml(); if (signAssertion) { SAMLAssertionSignature.Generate(samlAssertionXml, issuerX509Certificate.PrivateKey, issuerX509Certificate); } if (encryptAssertion) { var encryptedAssertion = new EncryptedAssertion(samlAssertionXml, partnerX509Certificate); samlResponse.Assertions.Add(encryptedAssertion.ToXml()); } else { samlResponse.Assertions.Add(samlAssertionXml); } var samlResponseXml = samlResponse.ToXml(); if (signResponse) { SAMLMessageSignature.Generate(samlResponseXml, issuerX509Certificate.PrivateKey, issuerX509Certificate); } return(samlResponseXml); }
private static Assertion CreateAssertion(SamlResponseFactoryArgs args) { var assertionId = AssertionIdFactory(); var issueInstant = IssueInstantFactory(); var version = VersionFactory(); var notOnOrAfter = issueInstant.DateTime.Add(args.TimeToBeExpired); var authnInstant = issueInstant.DateTime; var sessionIndex = string.IsNullOrEmpty(args.SessionIndex.Value) ? SessionIndexFactory() : args.SessionIndex.Value; var assertion = new Assertion { Issuer = new NameId(), Id = assertionId, IssueInstant = issueInstant.DateTime, Version = version, }; assertion.Issuer.Value = args.Issuer.Value; assertion.Subject = new Subject(); var subjectConfirmation = new SubjectConfirmation { Method = SubjectConfirmation.BearerMethod, SubjectConfirmationData = new SubjectConfirmationData { NotOnOrAfter = notOnOrAfter, Recipient = args.Recipient.Value, InResponseTo = args.RequestId.Value, }, }; assertion.Subject.Items = new object[] { new NameId { Format = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress", Value = args.Email.Value }, subjectConfirmation }; assertion.Conditions = new Conditions { NotOnOrAfter = notOnOrAfter }; var audienceRestriction = new AudienceRestriction { Audience = new List <string>(new[] { args.Audience.Value }) }; assertion.Conditions.Items = new List <ConditionAbstract>(new ConditionAbstract[] { audienceRestriction }); AuthnStatement authnStatement; { authnStatement = new AuthnStatement(); assertion.Items = new StatementAbstract[] { authnStatement }; authnStatement.AuthnInstant = authnInstant; authnStatement.SessionIndex = sessionIndex; authnStatement.AuthnContext = new AuthnContext { Items = new object[] { "urn:oasis:names:tc:SAML:2.0:ac:classes:X509" }, ItemsElementName = new[] { AuthnContextType.AuthnContextClassRef } }; } AttributeStatement attributeStatement; { attributeStatement = new AttributeStatement(); var email = new SamlAttribute { Name = "User.email", NameFormat = "urn:oasis:names:tc:SAML:2.0:attrname-format:basic", AttributeValue = new[] { args.Email.Value } }; attributeStatement.Items = new object[] { email }; } assertion.Items = new StatementAbstract[] { authnStatement, attributeStatement }; return(assertion); }
private void BuildSamlRequest() { ClientScript.RegisterStartupScript(typeof(Page), "OpaqueDivider", @" <script language=""javascript""> <!-- var dividerID = '" + this.SamlAgentDiv.ClientID + @"'; var divider = document.getElementById(dividerID); divider.style.visibility = 'visible'; //--> </script>" ); //Creating SAML response X509Certificate2 vendorCertificate = GetVendorCertificate(); X509Certificate2 selerixCertificate = GetSelerixCertificate(); //string assertionConsumerServiceURL = "SamlResponse.aspx"; string assertionConsumerServiceURL = "http://localhost:49000/login.aspx?Path=SAML_TEST"; string audienceName = "whatever audience"; SAMLResponse samlResponse = new SAMLResponse(); samlResponse.Destination = assertionConsumerServiceURL; Issuer issuer = new Issuer("Vendor"); samlResponse.Issuer = issuer; samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null); SAMLAssertion samlAssertion = new SAMLAssertion(); samlAssertion.Issuer = issuer; Subject subject = null; //subject = new Subject(new EncryptedID(new NameID(this._EmailText.Text), selerixCertificate, new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl))); subject = new Subject(new NameID(this._EmailText.Text)); SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer); SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData(); subjectConfirmationData.Recipient = assertionConsumerServiceURL; subjectConfirmationData.NotOnOrAfter = DateTime.UtcNow.AddHours(1); 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(audienceName)); conditions.ConditionsList.Add(audienceRestriction); samlAssertion.Conditions = conditions; AuthnStatement authnStatement = new AuthnStatement(); authnStatement.AuthnContext = new AuthnContext(); authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Unspecified); samlAssertion.Statements.Add(authnStatement); AttributeStatement attributeStatement = new AttributeStatement(); Transmittal transmittal = BuildTransmittal(); if (transmittal != null && !string.IsNullOrEmpty(this._FirstName.Text) && !string.IsNullOrEmpty(this._LastName.Text)) { attributeStatement.Attributes.Add(new SAMLAttribute("Transmittal", SAMLIdentifiers.AttributeNameFormats.Basic, null, SerializationHelper.SerializeToString(transmittal))); } samlAssertion.Statements.Add(attributeStatement); // EncryptedAssertion encryptedAssertion = new EncryptedAssertion(samlAssertion, selerixCertificate, new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl)); // samlResponse.Assertions.Add(encryptedAssertion); samlResponse.Assertions.Add(samlAssertion); //Created SAML response //Sending SAML response // Serialize the SAML response for transmission. XmlElement samlResponseXml = samlResponse.ToXml(); // Sign the SAML response. SAMLMessageSignature.Generate(samlResponseXml, vendorCertificate.PrivateKey, vendorCertificate); HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache"); HttpContext.Current.Response.AddHeader("Pragma", "no-cache"); IdentityProvider.SendSAMLResponseByHTTPPost(HttpContext.Current.Response, assertionConsumerServiceURL, samlResponseXml, "");// for test purposes }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); try { #region Custom Attributes // If you need to add custom attributes, uncomment the following code var attributeStatement = new AttributeStatement(); attributeStatement.Attributes.Add(new Atp.Saml2.Attribute("email", SamlAttributeNameFormat.Basic, null, "*****@*****.**")); attributeStatement.Attributes.Add(new Atp.Saml2.Attribute("FirstName", SamlAttributeNameFormat.Basic, null, "John")); attributeStatement.Attributes.Add(new Atp.Saml2.Attribute("LastName", SamlAttributeNameFormat.Basic, null, "Smith")); if (Session["username"] != null && Session["previoususername"] != null) { if (!Session["username"].ToString().ToLower().Equals(Session["previoususername"].ToString().ToLower())) attributeStatement.Attributes.Add(new Atp.Saml2.Attribute("samlsessionstate", SamlAttributeNameFormat.Basic, null, "new")); } #endregion // Set External Account Id for Metanga var externalAccountId = "XAF10964"; if (Session["username"] != null) { externalAccountId = Session["username"].ToString(); } else { Session["username"] = externalAccountId; Session["previoususername"] = externalAccountId; } var consumerServiceUrl = Helper.GetUrl("LinkSelfcareLogin"); // Use the local user's local identity. var subject = new Subject(new NameId(User.Identity.Name)) {NameId = {NameIdentifier = externalAccountId}}; subject.SubjectConfirmations.Add(new SubjectConfirmation(SamlSubjectConfirmationMethod.Bearer) { SubjectConfirmationData = new SubjectConfirmationData { Recipient = consumerServiceUrl } }); // Create a new authentication statement. var authnStatement = new AuthnStatement { AuthnContext = new AuthnContext { AuthnContextClassRef = new AuthnContextClassRef(SamlAuthenticateContext.Password) } }; var issuer = new Issuer(GetAbsoluteUrl("~/")); var samlAssertion = new Assertion { Issuer = issuer, Subject = subject }; samlAssertion.Statements.Add(authnStatement); samlAssertion.Statements.Add(attributeStatement); // Get the PFX certificate with Private Key. var filePath = Path.Combine(HttpRuntime.AppDomainAppPath, "metangasso.pfx"); const string pwd = "123"; var x509Certificate = new X509Certificate2(filePath, pwd, X509KeyStorageFlags.MachineKeySet); if (!x509Certificate.HasPrivateKey) return; // Create a SAML response object. var samlResponse = new Response { // Assign the consumer service url. Destination = consumerServiceUrl, Issuer = issuer, Status = new Status(SamlPrimaryStatusCode.Success, null) }; // Add assertion to the SAML response object. samlResponse.Assertions.Add(samlAssertion); // Sign the SAML response with the certificate. samlResponse.Sign(x509Certificate); var targetUrl = Helper.GetUrl("LinkSelfcareBilling") + "?SSO=true"; if (Session["SsoLink"] != null) { targetUrl = Session["SsoLink"].ToString(); } // Send the SAML response to the service provider. samlResponse.SendPostBindingForm(Response.OutputStream, consumerServiceUrl, targetUrl); } catch (Exception exception) { Trace.Write("IdentityProvider", "An Error occurred", exception); } }
private string BuildSAML() { var strIssuer = queryParameters.FirstOrDefault(i => i.Key == "issuer").Value; var member = queryParameters.FirstOrDefault(i => i.Key == "member").Value; var userEmail = queryParameters.FirstOrDefault(i => i.Key == "userEmail").Value; var cn = queryParameters.FirstOrDefault(i => i.Key == "cn").Value; var uid = queryParameters.FirstOrDefault(i => i.Key == "uid").Value; var pfxLocation = queryParameters.FirstOrDefault(i => i.Key == "pfxLocation").Value; var pfxPwd = queryParameters.FirstOrDefault(i => i.Key == "pfxPwd").Value; var samlResponse = new SAMLResponse(); samlResponse.Issuer = new Issuer(strIssuer); samlResponse.Destination = strIssuer; var samlAssertion = new SAMLAssertion(); samlAssertion.Issuer = new Issuer(strIssuer); samlAssertion.Subject = new Subject(new NameID(userEmail, null, null, SAMLIdentifiers.NameIdentifierFormats.EmailAddress, null)); samlAssertion.Conditions = new Conditions(new TimeSpan(1, 0, 0)); var authnStatement = new AuthnStatement(); authnStatement.AuthnContext = new AuthnContext(); authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.PasswordProtectedTransport); samlAssertion.Statements.Add(authnStatement); var attributeStatement = new AttributeStatement(); attributeStatement.Attributes.Add(new SAMLAttribute("member", SAMLIdentifiers.AttributeNameFormats.Basic, null, member)); samlAssertion.Statements.Add(attributeStatement); attributeStatement = new AttributeStatement(); attributeStatement.Attributes.Add(new SAMLAttribute("mail", SAMLIdentifiers.AttributeNameFormats.Basic, null, userEmail)); samlAssertion.Statements.Add(attributeStatement); attributeStatement = new AttributeStatement(); attributeStatement.Attributes.Add(new SAMLAttribute("cn", SAMLIdentifiers.AttributeNameFormats.Basic, null, cn)); samlAssertion.Statements.Add(attributeStatement); attributeStatement = new AttributeStatement(); attributeStatement.Attributes.Add(new SAMLAttribute("uid", SAMLIdentifiers.AttributeNameFormats.Basic, null, uid)); samlAssertion.Statements.Add(attributeStatement); samlResponse.Assertions.Add(samlAssertion); if (true) { var x509Certificate = Util.LoadSignKeyAndCertificate(pfxLocation, pfxPwd); var signedXml = new SignedXml(samlResponse.ToXml()); signedXml.SigningKey = x509Certificate.PrivateKey; var keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(x509Certificate)); signedXml.KeyInfo = keyInfo; // Create a reference to be signed. var reference = new Reference(); reference.Uri = "#" + samlAssertion.ID; var env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); signedXml.AddReference(reference); signedXml.ComputeSignature(); samlResponse.Signature = signedXml.GetXml(); } var result = samlResponse.ToXml().OuterXml.ToString(); File.WriteAllText("SAMLPayload.xml", result); return(Util.EncodeToBase64(result)); }
/// <summary> /// Assembles our basic test assertion /// </summary> /// <returns></returns> public static Assertion GetBasicAssertion() { Assertion assertion = new Assertion(); { assertion.Issuer = new NameID(); assertion.ID = "_b8977dc86cda41493fba68b32ae9291d"; assertion.IssueInstant = DateTime.UtcNow; assertion.Version = "2.0"; assertion.Issuer.Value = GetBasicIssuer(); } { assertion.Subject = new Subject(); SubjectConfirmation subjectConfirmation = new SubjectConfirmation(); subjectConfirmation.Method = SubjectConfirmation.BEARER_METHOD; subjectConfirmation.SubjectConfirmationData = new SubjectConfirmationData(); subjectConfirmation.SubjectConfirmationData.NotOnOrAfter = DateTime.UtcNow.AddMinutes(1); subjectConfirmation.SubjectConfirmationData.Recipient = "http://borger.dk"; assertion.Subject.Items = new object[] { subjectConfirmation }; } { assertion.Conditions = new Conditions(); assertion.Conditions.NotOnOrAfter = DateTime.UtcNow.AddMinutes(1); AudienceRestriction audienceRestriction = new AudienceRestriction(); audienceRestriction.Audience = GetAudiences(); assertion.Conditions.Items = new List <ConditionAbstract>(new ConditionAbstract[] { audienceRestriction }); } AuthnStatement authnStatement; { authnStatement = new AuthnStatement(); assertion.Items = new StatementAbstract[] { authnStatement }; authnStatement.AuthnInstant = new DateTime(2008, 1, 8); authnStatement.SessionIndex = "70225885"; authnStatement.AuthnContext = new AuthnContext(); authnStatement.AuthnContext.Items = new object[] { "urn:oasis:names:tc:SAML:2.0:ac:classes:X509", "http://www.safewhere.net/authncontext/declref" }; authnStatement.AuthnContext.ItemsElementName = new ItemsChoiceType5[] { ItemsChoiceType5.AuthnContextClassRef, ItemsChoiceType5.AuthnContextDeclRef }; } AttributeStatement attributeStatement; { attributeStatement = new AttributeStatement(); SamlAttribute surName = new SamlAttribute(); surName.FriendlyName = "SurName"; surName.Name = "urn:oid:2.5.4.4"; surName.NameFormat = SamlAttribute.NAMEFORMAT_URI; surName.AttributeValue = new string[] { "Fry" }; SamlAttribute commonName = new SamlAttribute(); commonName.FriendlyName = "CommonName"; commonName.Name = "urn:oid:2.5.4.3"; commonName.NameFormat = SamlAttribute.NAMEFORMAT_URI; commonName.AttributeValue = new string[] { "Philip J. Fry" }; SamlAttribute userName = new SamlAttribute(); userName.Name = "urn:oid:0.9.2342.19200300.100.1.1"; userName.NameFormat = SamlAttribute.NAMEFORMAT_URI; userName.AttributeValue = new string[] { "fry" }; SamlAttribute eMail = new SamlAttribute(); eMail.FriendlyName = "Email"; eMail.Name = "urn:oid:0.9.2342.19200300.100.1.3"; eMail.NameFormat = SamlAttribute.NAMEFORMAT_URI; eMail.AttributeValue = new string[] { "*****@*****.**" }; attributeStatement.Items = new object[] { surName, commonName, userName, eMail }; } assertion.Items = new StatementAbstract[] { authnStatement, attributeStatement }; return(assertion); }
private static string BuildSAMLRequest(IList <string> attributes) { var strIssuer = "https://sso.staging.gnohie.org/MirthSignOn-idp/ssoresp"; var samlResponse = new SAMLResponse(); samlResponse.Issuer = new Issuer(strIssuer); samlResponse.Destination = strIssuer; var samlAssertion = new SAMLAssertion(); samlAssertion.Issuer = new Issuer(strIssuer); samlAssertion.Subject = new Subject(new NameID(attributes.ElementAt(1), null, null, SAMLIdentifiers.NameIdentifierFormats.EmailAddress, null)); samlAssertion.Conditions = new Conditions(new TimeSpan(1, 0, 0)); var authnStatement = new AuthnStatement(); authnStatement.AuthnContext = new AuthnContext(); authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.PasswordProtectedTransport); samlAssertion.Statements.Add(authnStatement); var attributeStatement = new AttributeStatement(); attributeStatement.Attributes.Add(new SAMLAttribute("member", SAMLIdentifiers.AttributeNameFormats.Basic, null, attributes.ElementAt(0))); samlAssertion.Statements.Add(attributeStatement); attributeStatement = new AttributeStatement(); attributeStatement.Attributes.Add(new SAMLAttribute("mail", SAMLIdentifiers.AttributeNameFormats.Basic, null, attributes.ElementAt(1))); samlAssertion.Statements.Add(attributeStatement); attributeStatement = new AttributeStatement(); attributeStatement.Attributes.Add(new SAMLAttribute("cn", SAMLIdentifiers.AttributeNameFormats.Basic, null, attributes.ElementAt(2))); samlAssertion.Statements.Add(attributeStatement); attributeStatement = new AttributeStatement(); attributeStatement.Attributes.Add(new SAMLAttribute("uid", SAMLIdentifiers.AttributeNameFormats.Basic, null, attributes.ElementAt(3))); samlAssertion.Statements.Add(attributeStatement); samlResponse.Assertions.Add(samlAssertion); if (true) { var x509Certificate = Util.LoadSignKeyAndCertificate(); var signedXml = new SignedXml(samlResponse.ToXml()); signedXml.SigningKey = x509Certificate.PrivateKey; var keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(x509Certificate)); signedXml.KeyInfo = keyInfo; // Create a reference to be signed. var reference = new Reference(); reference.Uri = "#" + samlAssertion.ID; var env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); signedXml.AddReference(reference); signedXml.ComputeSignature(); samlResponse.Signature = signedXml.GetXml(); } //samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null); var result = samlResponse.ToXml().OuterXml.ToString(); File.WriteAllText("SAMLPayload.xml", result); return(Util.EncodeToBase64(result)); }
/// <summary> /// Properties the specified property. /// </summary> /// <param name="statement">The statement.</param> /// <param name="property">The property.</param> /// <returns>The Statement.</returns> public static Statement Property(this AttributeStatement statement, Property property) { statement.AddProperty(property); return(statement); }
/// <summary> /// Properties the specified label. /// </summary> /// <param name="statement">The statement.</param> /// <param name="label">The label.</param> /// <param name="value">The value.</param> /// <returns>The AttributeStatement.</returns> public static AttributeStatement Property(this AttributeStatement statement, string label, string value) { statement.AddProperty(new Property(label, value)); return(statement); }
// 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; }
public UnsignedSAMLResponse CreateAssertion(string id) { var attributeStatement = new AttributeStatement() { new SSOLibrary.Attribute() { AttributeValue = new AttributeValue() { Value = "*****@*****.**", Type = "asdasd" }, Name = "email", NameFormat = "string" }, new SSOLibrary.Attribute() { AttributeValue = new AttributeValue() { Value = "Lőrinc Sándor", Type = "name" }, Name = "name", NameFormat = "string" } }; var response = new UnsignedSAMLResponse() { Destination = "dest", ID = Guid.NewGuid().ToString(), InResponseTo = id, IssueInstant = DateTime.Now, Version = SAMLContants.Version, Status = new Status() { StatusCode = new StatusCode() { Value = "alma" } }, Issuer = "asdasd", Assertion = new Assertion() { AuthnStatement = new AuthnStatement() { AuthnContext = new AuthnContext() { AuthnContextClassRef = "asda" }, AuthnInstant = DateTime.Now, SessionIndex = "asdasd", SessionNotOnOrAfter = DateTime.Now.AddDays(12) }, ID = "adsasd", IssueInstant = DateTime.Now, Issuer = "asdasd", Subject = new Subject() { NameID = new NameID() { Format = "format", SPNameQualifier = "spname", Value = "value" }, SubjectConfirmation = new SubjectConfirmation() { Method = "method", SubjectConfirmationData = new SubjectConfirmationData() { InResponseTo = id, NotOnOrAfter = DateTime.Now, Recipient = "recipient" } } }, Version = SAMLContants.Version, Conditions = new Conditions() { AudienceRestriction = new AudienceRestriction() { Audience = "audience" }, NotBefore = DateTime.MaxValue, NotOnOrAfter = DateTime.MinValue }, AttributeStatement = attributeStatement } }; return(response); }
/// <summary> /// Handles the Click event of the submitButton control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void submitButton_Click(object sender, EventArgs e) { Transmittal transmittal = null; string employeeID = this._EmployeeID.Text; if (!string.IsNullOrEmpty(this._XMLText.Text)) { try { transmittal = (Transmittal)SerializationHelper.DeserializeFromString(this._XMLText.Text, typeof(Transmittal)); } catch (Exception exception) { this._XMLText.Text = exception.Message; Exception inner = exception.InnerException; while (inner != null) { this._XMLText.Text += "\n" + inner.Message; inner = inner.InnerException; } this._XMLText.Text = PrepareSourceCode(this._XMLText.Text); } } if (!string.IsNullOrEmpty(employeeID) && transmittal != null && transmittal.Applicants != null && transmittal.Applicants.Count > 0) { transmittal.Applicants[0].EmployeeIdent = employeeID; } Session["Transmittal"] = transmittal; //Creating SAML responce X509Certificate2 vendorCertificate = GetVendorCertificate(); X509Certificate2 selerixCertificate = GetSelerixCertificate(); string assertionConsumerServiceURL = "SamlResponse.aspx"; string audienceName = "whatever audience"; SAMLResponse samlResponse = new SAMLResponse(); samlResponse.Destination = assertionConsumerServiceURL; Issuer issuer = new Issuer("Vendor"); samlResponse.Issuer = issuer; samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null); SAMLAssertion samlAssertion = new SAMLAssertion(); samlAssertion.Issuer = issuer; Subject subject = null; // subject = new Subject(new EncryptedID(new NameID(employeeID), selerixCertificate, new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl))); //employee ID subject = new Subject(new NameID(employeeID)); //employee ID SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer); SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData(); subjectConfirmationData.Recipient = assertionConsumerServiceURL; subjectConfirmationData.NotOnOrAfter = DateTime.UtcNow.AddHours(1); 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(audienceName)); conditions.ConditionsList.Add(audienceRestriction); samlAssertion.Conditions = conditions; AuthnStatement authnStatement = new AuthnStatement(); authnStatement.AuthnContext = new AuthnContext(); authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Unspecified); samlAssertion.Statements.Add(authnStatement); AttributeStatement attributeStatement = new AttributeStatement(); if (transmittal != null) { attributeStatement.Attributes.Add(new SAMLAttribute("Transmittal", SAMLIdentifiers.AttributeNameFormats.Basic, null, SerializationHelper.SerializeToString(transmittal))); if (transmittal.Applicants != null && transmittal.Applicants.Count > 0) { transmittal.Applicants[0].EmployeeIdent = employeeID; } } //Check for Transmittal Options for (int i = 0; i < _TransmittalOptionsList.Items.Count; i++) { string answer = "no"; if (_TransmittalOptionsList.Items[i].Selected) { answer = "yes"; } if (_TransmittalOptionsList.Items[i].Value == "HeaderAndFooter") { attributeStatement.Attributes.Add(new SAMLAttribute("HeaderAndFooter", SAMLIdentifiers.AttributeNameFormats.Basic, null, answer)); } else if (_TransmittalOptionsList.Items[i].Value == "Sidebar") { attributeStatement.Attributes.Add(new SAMLAttribute("Sidebar", SAMLIdentifiers.AttributeNameFormats.Basic, null, answer)); } else if (_TransmittalOptionsList.Items[i].Value == "PersonalInfo") { attributeStatement.Attributes.Add(new SAMLAttribute("PersonalInfo", SAMLIdentifiers.AttributeNameFormats.Basic, null, answer)); } else if (_TransmittalOptionsList.Items[i].Value == "Welcome") { attributeStatement.Attributes.Add(new SAMLAttribute("Welcome", SAMLIdentifiers.AttributeNameFormats.Basic, null, answer)); } else if (_TransmittalOptionsList.Items[i].Value == "Review") { attributeStatement.Attributes.Add(new SAMLAttribute("Review", SAMLIdentifiers.AttributeNameFormats.Basic, null, answer)); } } samlAssertion.Statements.Add(attributeStatement); // EncryptedAssertion encryptedAssertion = new EncryptedAssertion(samlAssertion, selerixCertificate, new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl)); // samlResponse.Assertions.Add(encryptedAssertion); samlResponse.Assertions.Add(samlAssertion); //Created SAML response //Sending SAML response // Serialize the SAML response for transmission. XmlElement samlResponseXml = samlResponse.ToXml(); // Sign the SAML response. SAMLMessageSignature.Generate(samlResponseXml, vendorCertificate.PrivateKey, vendorCertificate); HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache"); HttpContext.Current.Response.AddHeader("Pragma", "no-cache"); IdentityProvider.SendSAMLResponseByHTTPPost(HttpContext.Current.Response, assertionConsumerServiceURL, samlResponseXml, "");// for test purposes }