private static void Serialize(SamlSubject samlSubject, XmlDocument document, XmlNode root) { if (samlSubject == null) { throw new ArgumentNullException(nameof(samlSubject)); } if (document == null) { throw new ArgumentNullException(nameof(document)); } if (root == null) { throw new ArgumentNullException(nameof(root)); } var subjectNode = document.CreateElement(Constants.XmlPrefixes.Saml, Constants.XmlRootNames.SamlSubject, Constants.XmlNamespaces.Saml); Serialize(samlSubject.NameIdentifier, document, subjectNode); if (samlSubject.SubjectConfirmation != null) { Serialize(samlSubject.SubjectConfirmation, document, subjectNode); } root.AppendChild(subjectNode); }
private static SamlAssertion CreateAssertion(ClaimSet claims, SecurityKey signatureKey, SecurityKeyIdentifier signatureKeyIdentifier, SecurityKeyIdentifier proofKeyIdentifier, SecurityAlgorithmSuite algoSuite) { SamlSubject samlSubject = new SamlSubject(null, null, "Self", new List <string>(1) { SamlConstants.HolderOfKey }, null, proofKeyIdentifier); IList <SamlAttribute> list = new List <SamlAttribute>(); foreach (Claim claim in claims) { if (typeof(string) == claim.Resource.GetType()) { list.Add(new SamlAttribute(claim)); } } SamlAttributeStatement item = new SamlAttributeStatement(samlSubject, list); List <SamlStatement> list2 = new List <SamlStatement>(); list2.Add(item); SigningCredentials signingCredentials = new SigningCredentials(signatureKey, algoSuite.DefaultAsymmetricSignatureAlgorithm, algoSuite.DefaultDigestAlgorithm, signatureKeyIdentifier); DateTime utcNow = DateTime.UtcNow; return(new SamlAssertion("_" + Guid.NewGuid().ToString(), "Self", utcNow, new SamlConditions(utcNow, utcNow + new TimeSpan(10, 0, 0)), new SamlAdvice(), list2) { SigningCredentials = signingCredentials }); }
public void WriteXmlValid() { SamlAssertion a = new SamlAssertion(); SamlSubject subject = new SamlSubject( SamlConstants.UserNameNamespace, "urn:myqualifier", "myname"); SamlAttribute attr = new SamlAttribute(Claim.CreateNameClaim("myname")); SamlAttributeStatement statement = new SamlAttributeStatement(subject, new SamlAttribute [] { attr }); a.Advice = new SamlAdvice(new string [] { "urn:testadvice1" }); DateTime notBefore = DateTime.SpecifyKind(new DateTime(2000, 1, 1), DateTimeKind.Utc); DateTime notOnAfter = DateTime.SpecifyKind(new DateTime(2006, 1, 1), DateTimeKind.Utc); a.Conditions = new SamlConditions(notBefore, notOnAfter); a.Statements.Add(statement); a.Issuer = "my_hero"; StringWriter sw = new StringWriter(); string id = a.AssertionId; DateTime instant = a.IssueInstant; using (XmlDictionaryWriter dw = CreateWriter(sw)) { a.WriteXml(dw, new SamlSerializer(), null); } string expected = String.Format("<?xml version=\"1.0\" encoding=\"utf-16\"?><saml:Assertion MajorVersion=\"1\" MinorVersion=\"1\" AssertionID=\"{0}\" Issuer=\"my_hero\" IssueInstant=\"{1}\" xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\"><saml:Conditions NotBefore=\"{3}\" NotOnOrAfter=\"{4}\" /><saml:Advice><saml:AssertionIDReference>urn:testadvice1</saml:AssertionIDReference></saml:Advice><saml:AttributeStatement><saml:Subject><saml:NameIdentifier Format=\"urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName\" NameQualifier=\"urn:myqualifier\">myname</saml:NameIdentifier></saml:Subject><saml:Attribute AttributeName=\"name\" AttributeNamespace=\"{2}\"><saml:AttributeValue>myname</saml:AttributeValue></saml:Attribute></saml:AttributeStatement></saml:Assertion>", id, instant.ToString("yyyy-MM-ddTHH:mm:ss.fff'Z'", CultureInfo.InvariantCulture), "http://schemas.xmlsoap.org/ws/2005/05/identity/claims", notBefore.ToString("yyyy-MM-ddTHH:mm:ss.fff'Z'", CultureInfo.InvariantCulture), notOnAfter.ToString("yyyy-MM-ddTHH:mm:ss.fff'Z'", CultureInfo.InvariantCulture)); Assert.AreEqual(expected, sw.ToString()); }
static void Main(string[] args) { // Here we create some SAML assertion with ID and Issuer name. SamlAssertion assertion = new SamlAssertion(); assertion.AssertionId = "AssertionID"; assertion.Issuer = "ISSUER"; // Create some SAML subject. SamlSubject samlSubject = new SamlSubject(); samlSubject.Name = "My Subject"; // // Create one SAML attribute with few values. SamlAttribute attr = new SamlAttribute(); attr.Namespace = "http://daenet.eu/saml"; attr.AttributeValues.Add("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. SamlAttributeStatement samlAttributeStatement = new SamlAttributeStatement(); samlAttributeStatement.Attributes.Add(attr); samlAttributeStatement.SamlSubject = samlSubject; // Append the statement to the SAML assertion. assertion.Statements.Add(samlAttributeStatement); }
/// <summary> /// Creates a SAML Token with the input parameters /// </summary> /// <param name="stsName">Name of the STS issuing the SAML Token</param> /// <param name="proofToken">Associated Proof Token</param> /// <param name="issuerToken">Associated Issuer Token</param> /// <param name="proofKeyEncryptionToken">Token to encrypt the proof key with</param> /// <param name="samlConditions">The Saml Conditions to be used in the construction of the SAML Token</param> /// <param name="samlAttributes">The Saml Attributes to be used in the construction of the SAML Token</param> /// <returns>A SAML Token</returns> public static SamlSecurityToken CreateSamlToken(string stsName, BinarySecretSecurityToken proofToken, SecurityToken issuerToken, SecurityToken proofKeyEncryptionToken, SamlConditions samlConditions, IEnumerable <SamlAttribute> samlAttributes) { // Create a security token reference to the issuer certificate SecurityKeyIdentifierClause skic = issuerToken.CreateKeyIdentifierClause <X509ThumbprintKeyIdentifierClause>(); SecurityKeyIdentifier issuerKeyIdentifier = new SecurityKeyIdentifier(skic); // Create an encrypted key clause containing the encrypted proof key byte[] wrappedKey = proofKeyEncryptionToken.SecurityKeys[0].EncryptKey(SecurityAlgorithms.RsaOaepKeyWrap, proofToken.GetKeyBytes()); SecurityKeyIdentifierClause encryptingTokenClause = proofKeyEncryptionToken.CreateKeyIdentifierClause <X509ThumbprintKeyIdentifierClause>(); EncryptedKeyIdentifierClause encryptedKeyClause = new EncryptedKeyIdentifierClause(wrappedKey, SecurityAlgorithms.RsaOaepKeyWrap, new SecurityKeyIdentifier(encryptingTokenClause)); SecurityKeyIdentifier proofKeyIdentifier = new SecurityKeyIdentifier(encryptedKeyClause); // Create a comfirmationMethod for HolderOfKey List <string> confirmationMethods = new List <string>(1); confirmationMethods.Add(SamlConstants.HolderOfKey); // Create a SamlSubject with proof key and confirmation method from above SamlSubject samlSubject = new SamlSubject(null, null, null, confirmationMethods, null, proofKeyIdentifier); // Create a SamlAttributeStatement from the passed in SamlAttribute collection and the SamlSubject from above SamlAttributeStatement samlAttributeStatement = new SamlAttributeStatement(samlSubject, samlAttributes); // Put the SamlAttributeStatement into a list of SamlStatements List <SamlStatement> samlSubjectStatements = new List <SamlStatement>(); samlSubjectStatements.Add(samlAttributeStatement); // Create a SigningCredentials instance from the key associated with the issuerToken. SigningCredentials signingCredentials = new SigningCredentials(issuerToken.SecurityKeys[0], SecurityAlgorithms.RsaSha1Signature, SecurityAlgorithms.Sha1Digest, issuerKeyIdentifier); // Create a SamlAssertion from the list of SamlStatements created above and the passed in // SamlConditions. SamlAssertion samlAssertion = new SamlAssertion("_" + Guid.NewGuid().ToString(), stsName, DateTime.UtcNow, samlConditions, new SamlAdvice(), samlSubjectStatements ); // Set the SigningCredentials for the SamlAssertion samlAssertion.SigningCredentials = signingCredentials; // Create a SamlSecurityToken from the SamlAssertion and return it return(new SamlSecurityToken(samlAssertion)); }
SamlSecurityToken GetSamlToken() { SamlAssertion a = new SamlAssertion(); SamlSubject subject = new SamlSubject( SamlConstants.UserNameNamespace, "urn:myqualifier", "myname"); SamlAttribute attr = new SamlAttribute(Claim.CreateNameClaim("myname")); SamlAttributeStatement statement = new SamlAttributeStatement(subject, new SamlAttribute [] { attr }); a.Statements.Add(statement); a.Issuer = "my_hero"; X509Certificate2 cert = new X509Certificate2(TestResourceHelper.GetFullPathOfResource("Test/Resources/test.pfx"), "mono"); X509AsymmetricSecurityKey key = new X509AsymmetricSecurityKey(cert); a.SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha1Signature, SecurityAlgorithms.Sha256Digest); XmlDocument doc = new XmlDocument(); XmlWriter w = doc.CreateNavigator().AppendChild(); using (XmlDictionaryWriter dw = XmlDictionaryWriter.CreateDictionaryWriter(w)) { a.WriteXml(dw, new SamlSerializer(), new MySecurityTokenSerializer()); } Console.Error.WriteLine(doc.OuterXml); return(new SamlSecurityToken(a)); }
public static SamlAssertion CreateSamlAssertionFromClaims(IEnumerable <Claim> claims) { var subject = new SamlSubject() { Name = "Windows Group Claim" }; var statement = new SamlAttributeStatement() { SamlSubject = subject }; var assertion = new SamlAssertion() { AssertionId = string.Format("_{0}", Guid.NewGuid().ToString()), Issuer = "System" }; foreach (var claim in claims) { var attribute = new SamlAttribute(claim); statement.Attributes.Add(attribute); } assertion.Statements.Add(statement); SignSamlAssertion(assertion); return(assertion); }
public static SamlAssertion CreateSamlAssertionFromUserNameClaims(IEnumerable <Claim> claims) { var subject = new SamlSubject() { Name = "Windows Group Claim" }; var statement = new SamlAttributeStatement() { SamlSubject = subject }; var assertion = new SamlAssertion() { AssertionId = string.Format("_{0}", Guid.NewGuid().ToString()), Issuer = "System" }; foreach (var claim in claims) { var samlClaim = new Claim(claim.ClaimType, GetResourceFromSid(claim.Resource as SecurityIdentifier), claim.Right); var attribute = new SamlAttribute(samlClaim); statement.Attributes.Add(attribute); } assertion.Statements.Add(statement); SignSamlAssertion(assertion); return(assertion); }
public void DefaultValues() { SamlSubject a = new SamlSubject(); Assert.IsNull(a.NameFormat, "#1"); Assert.IsNull(a.NameQualifier, "#2"); Assert.IsNull(a.Name, "#3"); }
/// <summary> /// Creates a SAML assertion based on input parameters /// </summary> /// <param name="claims">A ClaimSet containing the claims to be placed into the SAML assertion</param> /// <param name="signatureKey">The SecurityKey that will be used to sign the SAML assertion</param> /// <param name="signatureKeyIdentifier">A key identifier for the signature key</param> /// <param name="proofKeyIdentifier">A key identifier for the proof key</param> /// <param name="algoSuite">The algorithm suite to use when performing cryptographic operations</param> /// <returns>A SAML assertion containing the passed in claims and proof key, signed by the provided signature key</returns> private static SamlAssertion CreateAssertion(ClaimSet claims, SecurityKey signatureKey, SecurityKeyIdentifier signatureKeyIdentifier, SecurityKeyIdentifier proofKeyIdentifier, SecurityAlgorithmSuite algoSuite) { List <string> confirmationMethods = new List <string>(1); // Create a confirmationMethod for HolderOfKey confirmationMethods.Add(SamlConstants.HolderOfKey); // Create a SamlSubject with proof key and confirmation method from above SamlSubject samlSubject = new SamlSubject(null, null, "Self", confirmationMethods, null, proofKeyIdentifier); IList <SamlAttribute> samlAttributes = new List <SamlAttribute>(); foreach (Claim c in claims) { if (typeof(string) == c.Resource.GetType()) { samlAttributes.Add(new SamlAttribute(c)); } } // Create a SamlAttributeStatement from the passed in SamlAttribute collection and the // SamlSubject from above SamlAttributeStatement samlAttributeStatement = new SamlAttributeStatement(samlSubject, samlAttributes); // Put the SamlAttributeStatement into a list of SamlStatements List <SamlStatement> samlSubjectStatements = new List <SamlStatement>(); samlSubjectStatements.Add(samlAttributeStatement); // Create a SigningCredentials instance from the signature key SigningCredentials signingCredentials = new SigningCredentials(signatureKey, algoSuite.DefaultAsymmetricSignatureAlgorithm, algoSuite.DefaultDigestAlgorithm, signatureKeyIdentifier); // Create a SamlAssertion from the list of SamlStatements created above DateTime issueInstant = DateTime.UtcNow; SamlAssertion samlAssertion = new SamlAssertion("_" + Guid.NewGuid().ToString(), "Self", issueInstant, new SamlConditions(issueInstant, issueInstant + new TimeSpan(10, 0, 0)), new SamlAdvice(), samlSubjectStatements ); // Set the SigningCredentials for the SamlAssertion samlAssertion.SigningCredentials = signingCredentials; // Return the SamlAssertion return(samlAssertion); }
public void WriteXmlNoFormat() { SamlSubject a = new SamlSubject(); StringWriter sw = new StringWriter(); using (XmlDictionaryWriter dw = CreateWriter(sw)) { a.WriteXml(dw, new SamlSerializer(), null); } }
/// <summary> /// Creates a SAML token for the specified email address and security token. /// </summary> private SamlSecurityToken CreateSAMLToken( string emailAddress, X509SecurityToken issuerToken) { // Create list of confirmation strings List <string> confirmations = new List <string>(); // Add holder-of-key string to list of confirmation strings confirmations.Add("urn:oasis:names:tc:SAML:1.0:cm:bearer"); // Create SAML subject statement based on issuer member variable, confirmation string collection // local variable and proof key identifier parameter SamlSubject subject = new SamlSubject("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress", null, emailAddress); // Create a list of SAML attributes List <SamlAttribute> attributes = new List <SamlAttribute>(); Claim claim = Claim.CreateNameClaim(emailAddress); attributes.Add(new SamlAttribute(claim)); // Create list of SAML statements List <SamlStatement> statements = new List <SamlStatement>(); // Add a SAML attribute statement to the list of statements. Attribute statement is based on // subject statement and SAML attributes resulting from claims statements.Add(new SamlAttributeStatement(subject, attributes)); // Create a valid from/until condition DateTime validFrom = DateTime.UtcNow; DateTime validTo = DateTime.UtcNow.AddHours(12); SamlConditions conditions = new SamlConditions(validFrom, validTo); // Create the SAML assertion SamlAssertion assertion = new SamlAssertion( "_" + Guid.NewGuid().ToString(), issuerToken.Certificate.Subject, validFrom, conditions, null, statements); SecurityKey signingKey = new System.IdentityModel.Tokens.RsaSecurityKey((RSA)issuerToken.Certificate.PrivateKey); // Set the signing credentials for the SAML assertion assertion.SigningCredentials = new SigningCredentials( signingKey, System.IdentityModel.Tokens.SecurityAlgorithms.RsaSha1Signature, System.IdentityModel.Tokens.SecurityAlgorithms.Sha1Digest, new SecurityKeyIdentifier(issuerToken.CreateKeyIdentifierClause <X509ThumbprintKeyIdentifierClause>())); return(new SamlSecurityToken(assertion)); }
public void WriteXml1() { SamlSubject a = new SamlSubject("myFormat", "myQualifier", "myName"); StringWriter sw = new StringWriter(); using (XmlDictionaryWriter dw = CreateWriter(sw)) { a.WriteXml(dw, new SamlSerializer(), null); } Assert.AreEqual(String.Format("<?xml version=\"1.0\" encoding=\"utf-16\"?><saml:Subject xmlns:saml=\"{0}\"><saml:NameIdentifier Format=\"myFormat\" NameQualifier=\"myQualifier\">myName</saml:NameIdentifier></saml:Subject>", SamlConstants.Namespace), sw.ToString()); }
private static SamlAssertion CreateSamlAssertion(string issuer, string domain, string subject, Dictionary <string, string> attributes) { // Here we create some SAML assertion with ID and Issuer name. SamlAssertion assertion = new SamlAssertion(); assertion.AssertionId = "_" + Guid.NewGuid().ToString(); assertion.Issuer = issuer; //Not before, not after conditions assertion.Conditions = new SamlConditions(DateTime.UtcNow, DateTime.UtcNow.AddMinutes(10)); // // Create some SAML subject. SamlSubject samlSubject = new SamlSubject(); samlSubject.Name = subject; samlSubject.NameQualifier = subject; samlSubject.ConfirmationMethods.Add("urn:oasis:names:tc:SAML:1.0:cm:bearer"); // // Now create the SAML statement containing one attribute and one subject. SamlAttributeStatement samlAttributeStatement = new SamlAttributeStatement(); samlAttributeStatement.SamlSubject = samlSubject; // // Create userName SAML attributes. foreach (KeyValuePair <string, string> attribute in attributes) { SamlAttribute attr = new SamlAttribute(); attr.Name = attribute.Key; attr.Namespace = domain; attr.AttributeValues.Add(subject); samlAttributeStatement.Attributes.Add(attr); } // Append the statement to the SAML assertion. assertion.Statements.Add(samlAttributeStatement); IPHostEntry ipEntry = Dns.GetHostEntry(System.Environment.MachineName); SamlAuthenticationStatement samlAuthenticationStatement = new SamlAuthenticationStatement(samlSubject, "urn:oasis:names:tc:SAML:1.0:am:password", DateTime.UtcNow, null, ipEntry.AddressList[0].ToString(), null); assertion.Statements.Add(samlAuthenticationStatement); return(assertion); }
public void ReadXml1() { SamlSerializer ser = new SamlSerializer(); string xml = String.Format("<saml:Subject xmlns:saml=\"{0}\"><saml:NameIdentifier Format=\"myFormat\" NameQualifier=\"myQualifier\">myName</saml:NameIdentifier></saml:Subject>", SamlConstants.Namespace); XmlDictionaryReader reader = CreateReader(xml); reader.MoveToContent(); SamlSubject s = new SamlSubject(); s.ReadXml(reader, ser, null, null); Assert.AreEqual("myFormat", s.NameFormat, "#1"); Assert.AreEqual("myQualifier", s.NameQualifier, "#2"); Assert.AreEqual("myName", s.Name, "#3"); }
private SecurityToken CreateSAMLToken(DateTime validFrom, DateTime validTo, SecurityKey signingKey, SecurityKeyIdentifier signingKeyIdentifier, SecurityKeyIdentifier proofKeyIdentifier, IList <ClaimTypeRequirement> claimReqs) { // Create list of confirmation strings List <string> confirmations = new List <string>(); // Add holder-of-key string to list of confirmation strings confirmations.Add(SamlConstants.HolderOfKey); // Create SAML subject statement based on issuer member variable, confirmation string collection // local variable and proof key identifier parameter SamlSubject subject = new SamlSubject(null, null, issuer, confirmations, null, proofKeyIdentifier); // Create a list of SAML attributes List <SamlAttribute> attributes = new List <SamlAttribute>(); // Get the claimset we want to place into the SAML assertion ClaimSet cs = GetClaimSet(claimReqs); // Iterate through the claims and add a SamlAttribute for each claim // Note that GetClaimSet call above returns a claimset that only contains PossessProperty claims foreach (Claim c in cs) { attributes.Add(new SamlAttribute(c)); } // Create list of SAML statements List <SamlStatement> statements = new List <SamlStatement>(); // Add a SAML attribute statement to the list of statements. Attribute statement is based on // subject statement and SAML attributes resulting from claims statements.Add(new SamlAttributeStatement(subject, attributes)); // Create a valid from/until condition SamlConditions conditions = new SamlConditions(validFrom, validTo); // Create the SAML assertion SamlAssertion assertion = new SamlAssertion("_" + Guid.NewGuid().ToString(), issuer, validFrom, conditions, null, statements); // Set the signing credentials for the SAML assertion string signatureAlgorithm = GetSignatureAlgorithm(signingKey); assertion.SigningCredentials = new SigningCredentials(signingKey, signatureAlgorithm, SecurityAlgorithms.Sha1Digest, signingKeyIdentifier); SamlSecurityToken token = new SamlSecurityToken(assertion); Console.WriteLine("token.SecurityKeys.Count: {0}", token.SecurityKeys.Count); return(token); }
private SecurityToken CreateSAMLToken(DateTime validFrom, DateTime validTo, SecurityKey signingKey, SecurityKeyIdentifier signingKeyIdentifier, SecurityKeyIdentifier proofKeyIdentifier) { // Create list of confirmation strings List <string> confirmations = new List <string>(); // Add holder-of-key string to list of confirmation strings confirmations.Add("urn:oasis:names:tc:SAML:1.0:cm:holder-of-key"); // Create SAML subject statement based on issuer member variable, confirmation string collection // local variable and proof key identifier parameter SamlSubject subject = new SamlSubject(null, null, issuer, confirmations, null, proofKeyIdentifier); // Create a list of SAML attributes List <SamlAttribute> attributes = new List <SamlAttribute>(); // Get the claimset we want to place into the SAML assertion ClaimSet cs = GetClaimSet(); // Iterate through the claims and add a SamlAttribute for each claim // Note that GetClaimSet call above returns a claimset that only contains PossessProperty claims foreach (Claim c in cs) { attributes.Add(new SamlAttribute(c)); } // Create list of SAML statements List <SamlStatement> statements = new List <SamlStatement>(); // Add a SAML attribute statement to the list of statements. Attribute statement is based on // subject statement and SAML attributes resulting from claims statements.Add(new SamlAttributeStatement(subject, attributes)); // Create a valid from/until condition SamlConditions conditions = new SamlConditions(validFrom, validTo); // Add a audience Uri restriction conditions.Conditions.Add(new SamlAudienceRestrictionCondition(new Uri[] { new Uri("http://localhost:8010/fedservice/calc") })); // Create the SAML assertion SamlAssertion assertion = new SamlAssertion("_" + Guid.NewGuid().ToString(), issuer, validFrom, conditions, null, statements); // Set the signing credentials for the SAML assertion string signatureAlgorithm = GetSignatureAlgorithm(signingKey); assertion.SigningCredentials = new SigningCredentials(signingKey, signatureAlgorithm, SecurityAlgorithms.Sha1Digest, signingKeyIdentifier); return(new SamlSecurityToken(assertion)); }
public void WriteXml1() { SamlAttribute attr = new SamlAttribute(Claim.CreateNameClaim("myname")); SamlSubject subject = new SamlSubject( SamlConstants.UserNameNamespace, "urn:myqualifier", "myname"); SamlAttributeStatement s = new SamlAttributeStatement( subject, new SamlAttribute [] { attr }); StringWriter sw = new StringWriter(); using (XmlDictionaryWriter dw = CreateWriter(sw)) { s.WriteXml(dw, new SamlSerializer(), null); } Assert.AreEqual(String.Format("<?xml version=\"1.0\" encoding=\"utf-16\"?><saml:AttributeStatement xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\"><saml:Subject><saml:NameIdentifier Format=\"urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName\" NameQualifier=\"urn:myqualifier\">myname</saml:NameIdentifier></saml:Subject><saml:Attribute AttributeName=\"name\" AttributeNamespace=\"{0}\"><saml:AttributeValue>myname</saml:AttributeValue></saml:Attribute></saml:AttributeStatement>", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims"), sw.ToString()); }
public SoapEnvelope Build() { CheckInit(); var samlAssertionId = GenerateId("assertion"); var requestId = GenerateId("request"); var bodyId = GenerateId("id"); var timeStampId = GenerateId("TS"); var x509Id = GenerateId("X509"); var ssin = GetSsin(_x509Certificate.Subject); if (string.IsNullOrWhiteSpace(ssin)) { throw new EhealthException(Constants.ErrorCodes.NoSerialNumber); } var identitySubject = ParseSubject(_x509Certificate.Subject); var issuerSubject = ParseSubject(_x509Certificate.Issuer); _samlAttributes.Add(new SamlAttribute(Constants.EhealthStsNames.SsinCertHolderAttributeName, Constants.EhealthStsNames.SsinAttributeNamespace, ssin)); _samlAttributes.Add(new SamlAttribute(Constants.EhealthStsNames.SsinAttributeName, Constants.EhealthStsNames.SsinAttributeNamespace, ssin)); _samlAttributeDesignators.Add(new SamlAttributeDesignator(Constants.EhealthStsNames.SsinCertHolderAttributeName, Constants.EhealthStsNames.SsinAttributeNamespace)); _samlAttributeDesignators.Add(new SamlAttributeDesignator(Constants.EhealthStsNames.SsinAttributeName, Constants.EhealthStsNames.SsinAttributeNamespace)); var issueInstant = DateTime.Now; var samlNameIdentifier = new SamlNameIdentifier( Constants.EhealthStsNames.NameIdentifierFormat, issuerSubject, identitySubject); var samlSubject = new SamlSubject(samlNameIdentifier); var samlConditions = new SamlConditions(issueInstant); var samlAttributeStatement = new SamlAttributeStatement(samlSubject, _samlAttributes); var samlAssertion = new SamlAssertion(samlAssertionId, issueInstant, identitySubject, samlConditions, samlAttributeStatement); var subjectConfirmationData = new SamlSubjectConfirmationData(samlAssertion); var subjectConfirmation = new SamlSubjectConfirmation(Constants.EhealthStsNames.SubjectConfirmationMethod, _x509Certificate, subjectConfirmationData); var samlSubjectO = new SamlSubject(samlNameIdentifier, subjectConfirmation); var samlAttributeQuery = new SamlAttributeQuery(samlSubjectO, _samlAttributeDesignators); var samlRequest = new SamlRequest(requestId, samlAttributeQuery); var body = new SoapBody(samlRequest, bodyId); var soapSecurity = new SoapSecurity(DateTime.UtcNow, timeStampId, x509Id, _x509Certificate); var header = new SoapHeader(soapSecurity); var soapEnvelope = new SoapEnvelope(header, body); return(soapEnvelope); }
public static SamlSecurityToken CreateSamlToken(string issuedBy, string subject, string attrNamespace, Dictionary <string, string> claims, string certThumbPrint) { SamlAssertion assertion = new SamlAssertion(); assertion.AssertionId = string.Format("icfi_{0}", Guid.NewGuid().ToString()); assertion.Issuer = issuedBy; SamlSubject subj = new SamlSubject(); subj.Name = subject; SamlAttributeStatement samlAttrStatement = new SamlAttributeStatement(); foreach (string claimKey in claims.Keys) { SamlAttribute attr = new SamlAttribute(); attr.Namespace = attrNamespace; attr.AttributeValues.Add(claims[claimKey]); samlAttrStatement.Attributes.Add(attr); } samlAttrStatement.SamlSubject = subj; assertion.Statements.Add(samlAttrStatement); X509Certificate2 cert = GetCertificate(certThumbPrint); X509AsymmetricSecurityKey signingKey = new X509AsymmetricSecurityKey(cert); assertion.SigningCredentials = new SigningCredentials( signingKey, cert.PublicKey.Key.SignatureAlgorithm, SecurityAlgorithms.Sha1Digest, new SecurityKeyIdentifier(new X509ThumbprintKeyIdentifierClause(cert))); SamlSecurityToken samlToken = new SamlSecurityToken(assertion); return(samlToken); }
/// <summary> /// Build the contents of the SAML token /// </summary> /// <param name="writer"><b>XmlDictionaryWriter</b> to write the contents of this token to</param> protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { // Subject SamlSubject subject = new SamlSubject(); if (this.useKey != null) { // Add the key and the Holder-Of-Key confirmation method subject.KeyIdentifier = this.useKey; subject.ConfirmationMethods.Add(SamlConstants.HolderOfKey); } else { // This is a bearer token subject.ConfirmationMethods.Add(SamlConstants.SenderVouches); } // Attributes, statements, conditions, and assertions List <SamlStatement> statements = new List <SamlStatement>(); List <SamlAttribute> attributes = GetTokenAttributes(); statements.Add(new SamlAuthenticationStatement(subject, Constants.Saml.AuthenticationMethods.Unspecified, DateTime.Now, null, null, null)); statements.Add(new SamlAttributeStatement(subject, attributes)); SamlConditions conditions = new SamlConditions(DateTime.Now, (DateTime.Now + TimeSpan.FromHours(8.0))); SamlAssertion assertion = new SamlAssertion("uuid-" + Guid.NewGuid(), Program.Issuer, DateTime.Now, conditions, null, statements); // Build the signing token SecurityToken signingToken = new X509SecurityToken(Program.SigningCertificate); SecurityKeyIdentifier keyIdentifier = new SecurityKeyIdentifier(signingToken.CreateKeyIdentifierClause <X509RawDataKeyIdentifierClause>()); SigningCredentials signingCredentials = new SigningCredentials(signingToken.SecurityKeys[0], SecurityAlgorithms.RsaSha1Signature, SecurityAlgorithms.Sha1Digest, keyIdentifier); assertion.SigningCredentials = signingCredentials; // Build the SAML token SamlSecurityToken token = new SamlSecurityToken(assertion); SecurityKeyIdentifierClause attachedReference = token.CreateKeyIdentifierClause <SamlAssertionKeyIdentifierClause>(); SecurityKeyIdentifierClause unattachedReference = token.CreateKeyIdentifierClause <SamlAssertionKeyIdentifierClause>(); // // Write the XML // //writer = XmlDictionaryWriter.CreateTextWriter(File.CreateText("output.xml").BaseStream); // RSTR writer.WriteStartElement(Constants.WSTrust.NamespaceUri.Prefix, Constants.WSTrust.Elements.RequestSecurityTokenResponse, Constants.WSTrust.NamespaceUri.Uri); if (context != null) { writer.WriteAttributeString(Constants.WSTrust.Attributes.Context, context); } // TokenType writer.WriteElementString(Constants.WSTrust.NamespaceUri.Prefix, Constants.WSTrust.Elements.TokenType, Constants.WSTrust.NamespaceUri.Uri, Constants.WSTrust.TokenTypes.Saml10Assertion); // RequestedSecurityToken (the SAML token) SecurityTokenSerializer tokenSerializer = new WSSecurityTokenSerializer(); writer.WriteStartElement(Constants.WSTrust.NamespaceUri.Prefix, Constants.WSTrust.Elements.RequestedSecurityToken, Constants.WSTrust.NamespaceUri.Uri); tokenSerializer.WriteToken(writer, token); writer.WriteEndElement(); // RequestedAttachedReference writer.WriteStartElement(Constants.WSTrust.NamespaceUri.Prefix, Constants.WSTrust.Elements.RequestedAttachedReference, Constants.WSTrust.NamespaceUri.Uri); tokenSerializer.WriteKeyIdentifierClause(writer, attachedReference); writer.WriteEndElement(); // RequestedUnattachedReference writer.WriteStartElement(Constants.WSTrust.NamespaceUri.Prefix, Constants.WSTrust.Elements.RequestedUnattachedReference, Constants.WSTrust.NamespaceUri.Uri); tokenSerializer.WriteKeyIdentifierClause(writer, unattachedReference); writer.WriteEndElement(); // RequestedDisplayToken (display token) string displayTokenNS = "http://schemas.xmlsoap.org/ws/2005/05/identity"; writer.WriteStartElement("wsid", "RequestedDisplayToken", displayTokenNS); writer.WriteStartElement("wsid", "DisplayToken", displayTokenNS); foreach (SamlAttribute attribute in attributes) { writer.WriteStartElement("wsid", "DisplayClaim", displayTokenNS); writer.WriteAttributeString("Uri", attribute.Namespace + "/" + attribute.Name); writer.WriteStartElement("wsid", "DisplayTag", displayTokenNS); writer.WriteValue(attribute.Name); writer.WriteEndElement(); writer.WriteStartElement("wsid", "Description", displayTokenNS); writer.WriteValue(attribute.Namespace + "/" + attribute.Name); writer.WriteEndElement(); foreach (string attributeValue in attribute.AttributeValues) { writer.WriteStartElement("wsid", "DisplayValue", displayTokenNS); writer.WriteValue(attributeValue); writer.WriteEndElement(); } writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteEndElement(); // RSTR End writer.WriteEndElement(); //writer.Close(); }
public void SetFormatEmpty() { SamlSubject a = new SamlSubject(); a.NameFormat = String.Empty; }
public void SetQualifierEmpty() { SamlSubject a = new SamlSubject(); a.NameQualifier = String.Empty; }
public void SetNameEmpty() { SamlSubject a = new SamlSubject(); a.Name = String.Empty; }
/// <summary> /// Creates a SAML token for the specified email address. /// </summary> public static async System.Threading.Tasks.Task <UserIdentity> CreateSAMLTokenAsync(string emailAddress) { // Normally this would be done by a server that is capable of verifying that // the user is a legimate holder of email address. Using a local certficate to // signed the SAML token is a short cut that would never be done in a real system. CertificateIdentifier userid = new CertificateIdentifier(); userid.StoreType = CertificateStoreType.X509Store; userid.StorePath = "LocalMachine\\My"; userid.SubjectName = "UA Sample Client"; X509Certificate2 certificate = await userid.Find(); X509SecurityToken signingToken = new X509SecurityToken(certificate); // Create list of confirmation strings List <string> confirmations = new List <string>(); // Add holder-of-key string to list of confirmation strings confirmations.Add("urn:oasis:names:tc:SAML:1.0:cm:bearer"); // Create SAML subject statement based on issuer member variable, confirmation string collection // local variable and proof key identifier parameter SamlSubject subject = new SamlSubject("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress", null, emailAddress); // Create a list of SAML attributes List <SamlAttribute> attributes = new List <SamlAttribute>(); Claim claim = Claim.CreateNameClaim(emailAddress); attributes.Add(new SamlAttribute(claim)); // Create list of SAML statements List <SamlStatement> statements = new List <SamlStatement>(); // Add a SAML attribute statement to the list of statements. Attribute statement is based on // subject statement and SAML attributes resulting from claims statements.Add(new SamlAttributeStatement(subject, attributes)); // Create a valid from/until condition DateTime validFrom = DateTime.UtcNow; DateTime validTo = DateTime.UtcNow.AddHours(12); SamlConditions conditions = new SamlConditions(validFrom, validTo); // Create the SAML assertion SamlAssertion assertion = new SamlAssertion( "_" + Guid.NewGuid().ToString(), signingToken.Certificate.Subject, validFrom, conditions, null, statements); SecurityKey signingKey = new System.IdentityModel.Tokens.RsaSecurityKey((RSA)signingToken.Certificate.PrivateKey); // Set the signing credentials for the SAML assertion assertion.SigningCredentials = new SigningCredentials( signingKey, System.IdentityModel.Tokens.SecurityAlgorithms.RsaSha1Signature, System.IdentityModel.Tokens.SecurityAlgorithms.Sha1Digest, new SecurityKeyIdentifier(signingToken.CreateKeyIdentifierClause <X509ThumbprintKeyIdentifierClause>())); // TODO // return new UserIdentity(new SamlSecurityToken(assertion)); throw new NotImplementedException(); }
private SamlAssertion CreateSamlAssertion(SecurityKey signatureKey, SecurityKeyIdentifier signatureKeyIdentifier, SecurityKeyIdentifier proofKeyIdentifier) { Claim claim = base.ClientCredentials.Claims.FirstOrDefault((Claim c) => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"); if (claim == null) { throw new ArgumentException("At least one NameIdentifier/Identity claim must be present in the claimset", "ClaimsClientCredentials.Claims"); } SamlSubject samlSubject = new SamlSubject { NameFormat = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified", Name = claim.Value, KeyIdentifier = proofKeyIdentifier }; samlSubject.ConfirmationMethods.Add(SamlConstants.HolderOfKey); IEnumerable <SamlAttribute> enumerable = from c in base.ClientCredentials.Claims.Except(new Claim[] { claim }) select new SamlAttribute(SamlConstants.Namespace, c.Type, new string[] { c.Value }); if (base.ClientCredentials.Claims.FirstOrDefault((Claim c) => c.Type == "http://www.tridion.com/2009/08/directoryservice/claims/directoryServiceName") == null) { SamlAttribute samlAttribute = new SamlAttribute(SamlConstants.Namespace, "http://www.tridion.com/2009/08/directoryservice/claims/directoryServiceName", new string[] { claim.Issuer }); enumerable = enumerable.Concat(new SamlAttribute[] { samlAttribute }); } DateTime utcNow = DateTime.UtcNow; SamlAssertion samlAssertion = new SamlAssertion { AssertionId = "_" + Guid.NewGuid(), Issuer = claim.Issuer, IssueInstant = utcNow, Advice = new SamlAdvice(), SigningCredentials = new SigningCredentials(signatureKey, base.SecurityAlgorithmSuite.DefaultAsymmetricSignatureAlgorithm, base.SecurityAlgorithmSuite.DefaultDigestAlgorithm, signatureKeyIdentifier) }; samlAssertion.Statements.Add(new SamlAttributeStatement(samlSubject, enumerable)); if (base.ClientCredentials.AudienceUris != null) { IEnumerable <SamlCondition> conditions = new SamlAudienceRestrictionCondition[] { new SamlAudienceRestrictionCondition(base.ClientCredentials.AudienceUris) }; samlAssertion.Conditions = new SamlConditions(utcNow, utcNow + base.TokenValidityTimeSpan, conditions); } else { samlAssertion.Conditions = new SamlConditions(utcNow, utcNow + base.TokenValidityTimeSpan); } return(samlAssertion); }