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()); }
/// <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)); }
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); }
private static void Serialize(SamlAssertion samlAssertion, XmlDocument document, XmlNode root) { if (samlAssertion == null) { throw new ArgumentNullException(nameof(samlAssertion)); } if (document == null) { throw new ArgumentNullException(nameof(document)); } if (root == null) { throw new ArgumentNullException(nameof(root)); } var assertionNode = document.CreateElement(Constants.XmlPrefixes.Saml, Constants.XmlRootNames.SamlAssertion, Constants.XmlNamespaces.Saml); assertionNode.SetAttribute($"xmlns:{Constants.XmlPrefixes.Ns4}", Constants.XmlNamespaces.Ns4); assertionNode.SetAttribute(Constants.XmlAttributeNames.SamlAssertionId, samlAssertion.AssertionId); assertionNode.SetAttribute(Constants.XmlAttributeNames.SamlIssueInstant, ConvertToCurrentTime(samlAssertion.IssueInstant)); assertionNode.SetAttribute(Constants.XmlAttributeNames.SamlIssuer, samlAssertion.Issuer); assertionNode.SetAttribute(Constants.XmlAttributeNames.SamlMajorVersion, samlAssertion.MajorVersion.ToString()); assertionNode.SetAttribute(Constants.XmlAttributeNames.SamlMinorVersion, samlAssertion.MinorVersion.ToString()); Serialize(samlAssertion.Conditions, document, assertionNode); Serialize(samlAssertion.AttributeStatement, document, assertionNode); root.AppendChild(assertionNode); }
/// <summary> /// Copy constructor /// </summary> /// <param name="other">The SamlClientCredentials to create a copy of</param> protected SamlClientCredentials(SamlClientCredentials other) : base(other) { // Just do reference copy given sample nature this.assertion = other.assertion; this.claims = other.claims; this.proofToken = other.proofToken; }
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)); }
// Used in: How To: Create Security Token Service. //<snippet1> void AddSigningCredentials(SamlAssertion assertion, SecurityKey signingKey) { SigningCredentials sc = new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha1Signature, SecurityAlgorithms.Sha1Digest); assertion.SigningCredentials = sc; }
private static IEnumerable <SamlAssertion> ParseAssertions(XmlNode responseNode, SamlOptions options) { //All Assertions as direct child of Response-Element, or wrapped in EncryptedAssertion var assertions = responseNode.SelectNodes($"{SamlAuthenticationDefaults.SamlAssertionNsPrefix}:Assertion | {SamlAuthenticationDefaults.SamlAssertionNsPrefix}:EncryptedAssertion/{SamlAuthenticationDefaults.SamlAssertionNsPrefix}:Assertion", SamlXmlExtensions.NamespaceManager); var result = new List <SamlAssertion>(); for (var i = 0; i < assertions.Count; i++) { var assertion = new SamlAssertion(); var assertionNode = assertions[i]; assertion.Issuer = assertionNode.SelectSingleNode($"{SamlAuthenticationDefaults.SamlAssertionNsPrefix}:Issuer", SamlXmlExtensions.NamespaceManager)?.InnerText; assertion.Id = assertionNode.SelectSingleNode("@ID", SamlXmlExtensions.NamespaceManager)?.Value; var signatureNode = assertionNode.SelectSingleNode("ds:Signature", SamlXmlExtensions.NamespaceManager); if (signatureNode != null && options.IdentityProviderCertificate != null) { var signedXml = new SignedXml(assertionNode.OwnerDocument); signedXml.LoadXml((XmlElement)signatureNode); assertion.HasValidSignature = signedXml.CheckSignature(options.IdentityProviderCertificate, true); } var attributeStatements = assertionNode.SelectNodes($"{SamlAuthenticationDefaults.SamlAssertionNsPrefix}:AttributeStatement", SamlXmlExtensions.NamespaceManager); assertion.Attributes = ParseAttributeStatements(attributeStatements, options); assertion.SessionIndex = assertionNode.SelectSingleNode($"{SamlAuthenticationDefaults.SamlAssertionNsPrefix}:AuthnStatement/@SessionIndex", SamlXmlExtensions.NamespaceManager)?.Value; assertion.SubjectNameId = assertionNode.SelectSingleNode($"{SamlAuthenticationDefaults.SamlAssertionNsPrefix}:Subject/{SamlAuthenticationDefaults.SamlAssertionNsPrefix}:NameID", SamlXmlExtensions.NamespaceManager)?.InnerText; result.Add(assertion); } return(result); }
public override SecurityTokenProvider CreateSecurityTokenProvider(SecurityTokenRequirement tokenRequirement) { if (tokenRequirement.TokenType == SecurityTokenTypes.Saml || tokenRequirement.TokenType == "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1") { SamlAssertion samlAssertion = this.samlClientCredentials.Assertion; SecurityToken securityToken = this.samlClientCredentials.ProofToken; if (samlAssertion == null || securityToken == null) { SecurityBindingElement securityBindingElement = null; SecurityAlgorithmSuite algoSuite = null; if (tokenRequirement.TryGetProperty <SecurityBindingElement>("http://schemas.microsoft.com/ws/2006/05/servicemodel/securitytokenrequirement/SecurityBindingElement", out securityBindingElement)) { algoSuite = securityBindingElement.DefaultAlgorithmSuite; } if (tokenRequirement.KeyType == SecurityKeyType.SymmetricKey) { securityToken = SamlUtilities.CreateSymmetricProofToken(tokenRequirement.KeySize); samlAssertion = SamlUtilities.CreateSymmetricKeyBasedAssertion(this.samlClientCredentials.Claims, new X509SecurityToken(this.samlClientCredentials.ClientCertificate.Certificate), new X509SecurityToken(this.samlClientCredentials.ServiceCertificate.DefaultCertificate), (BinarySecretSecurityToken)securityToken, algoSuite); } else { securityToken = SamlUtilities.CreateAsymmetricProofToken(); samlAssertion = SamlUtilities.CreateAsymmetricKeyBasedAssertion(this.samlClientCredentials.Claims, securityToken, algoSuite); } } return(new SamlSecurityTokenProvider(samlAssertion, securityToken)); } return(base.CreateSecurityTokenProvider(tokenRequirement)); }
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 WriteXmlNullIssuer() { SamlAssertion a = new SamlAssertion(); using (XmlDictionaryWriter dw = CreateWriter(new StringWriter())) { a.WriteXml(dw, null, null); } }
public void WriteXmlNoStatement() { SamlAssertion a = new SamlAssertion(); a.Issuer = "my_boss"; using (XmlDictionaryWriter dw = CreateWriter(new StringWriter())) { a.WriteXml(dw, null, null); } }
/// <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 WriteXmlNullSerializer() { SamlAssertion a = new SamlAssertion(); a.Statements.Add(new SamlAttributeStatement()); a.Issuer = "my_hero"; using (XmlDictionaryWriter dw = CreateWriter(new StringWriter())) { a.WriteXml(dw, null, 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)); }
private static void SignSamlAssertion(SamlAssertion assertion) { var certificate2 = GetCertificateFromStore(System.Configuration.ConfigurationManager.AppSettings["TokenSigningCeritificate"]); var securityKey = new X509AsymmetricSecurityKey(certificate2); assertion.SigningCredentials = new SigningCredentials( securityKey, SecurityAlgorithms.RsaSha1Signature, SecurityAlgorithms.Sha1Digest, new SecurityKeyIdentifier(new X509ThumbprintKeyIdentifierClause(certificate2))); }
/// <summary> /// Creates the custom SecurityTokenProvider when SAML tokens are specified in the tokenRequirement /// </summary> /// <param name="tokenRequirement">A SecurityTokenRequirement </param> /// <returns>The appropriate SecurityTokenProvider</returns> public override SecurityTokenProvider CreateSecurityTokenProvider(SecurityTokenRequirement tokenRequirement) { // If token requirement matches SAML token return the custom SAML token provider if (tokenRequirement.TokenType == SecurityTokenTypes.Saml || tokenRequirement.TokenType == "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1") { // Retrieve the SAML assertion and proof token from the client credentials SamlAssertion assertion = this.samlClientCredentials.Assertion; SecurityToken prooftoken = this.samlClientCredentials.ProofToken; // If either the assertion of proof token is null... if (assertion == null || prooftoken == null) { // ...get the SecurityBindingElement and then the specified algorithm suite SecurityBindingElement sbe = null; SecurityAlgorithmSuite sas = null; if (tokenRequirement.TryGetProperty <SecurityBindingElement>("http://schemas.microsoft.com/ws/2006/05/servicemodel/securitytokenrequirement/SecurityBindingElement", out sbe)) { sas = sbe.DefaultAlgorithmSuite; } // If the token requirement is for a SymmetricKey based token.. if (tokenRequirement.KeyType == SecurityKeyType.SymmetricKey) { // Create a symmetric proof token prooftoken = SamlUtilities.CreateSymmetricProofToken(tokenRequirement.KeySize); // and a corresponding assertion based on the claims specified in the client credentials assertion = SamlUtilities.CreateSymmetricKeyBasedAssertion(this.samlClientCredentials.Claims, new X509SecurityToken(samlClientCredentials.ClientCertificate.Certificate), new X509SecurityToken(samlClientCredentials.ServiceCertificate.DefaultCertificate), (BinarySecretSecurityToken)prooftoken, sas); } // otherwise... else { // Create an asymmetric proof token prooftoken = SamlUtilities.CreateAsymmetricProofToken(); // and a corresponding assertion based on the claims specified in the client credentials assertion = SamlUtilities.CreateAsymmetricKeyBasedAssertion(this.samlClientCredentials.Claims, prooftoken, sas); } } // Create a SamlSecurityTokenProvider based on the assertion and proof token return(new SamlSecurityTokenProvider(assertion, prooftoken)); } // otherwise use base implementation else { return(base.CreateSecurityTokenProvider(tokenRequirement)); } }
public static List <string> GetAttributeValues(SamlAssertion assertion, string attributeName) { throw new NotImplementedException(); /*return assertion.getAttributeStatements() * .stream() * .flatMap(x->x.getAttributes().stream()) * .filter(x->attributeName.equals(x.getName())) * .flatMap(x->x.getAttributeValues().stream()) * .map(AssertionUtils::getAttributeValue) * .filter(x->x != null && !x.isEmpty()) * .collect(Collectors.toList());*/ }
public void TestMethod() { string[] attributeValues = { "test-value" }; SamlAttribute samlAttribute = new SamlAttribute("urn:namespace", "attributeName", attributeValues); Console.WriteLine("saml attribute: " + samlAttribute); SamlAuthenticationStatement samlStatement = new SamlAuthenticationStatement(); SamlAssertion samlAssertion = new SamlAssertion(); samlAssertion.Statements.Add(samlStatement); }
public void WriteXmlWithoutSamlSubject() { SamlAssertion a = new SamlAssertion(); a.Statements.Add(new SamlAttributeStatement()); a.Issuer = "my_boss"; StringWriter sw = new StringWriter(); using (XmlDictionaryWriter dw = CreateWriter(sw)) { a.WriteXml(dw, new SamlSerializer(), null); } Assert.AreEqual("<?xml version=\"1.0\" ?>", sw.ToString()); }
private static string SerializeToken(SamlAssertion assertion) { SamlSecurityToken token = new SamlSecurityToken(assertion); SamlSerializer serializer = new SamlSerializer(); WSSecurityTokenSerializer tokenSerializer = new WSSecurityTokenSerializer(); StringWriter stringWriter = new StringWriter(); XmlTextWriter xmltextWriter = new XmlTextWriter(stringWriter); serializer.WriteToken(token, xmltextWriter, tokenSerializer); return(stringWriter.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); }
private static void SignSamlAssertion(SamlAssertion assertion) { var certificate2 = GetCertificateFromStore(StoreLocation.CurrentUser, DateTime.Now, "CN=SamlTokenSigningCertificate"); if (certificate2 != null) { var securityKey = new X509AsymmetricSecurityKey(certificate2); assertion.SigningCredentials = new SigningCredentials( securityKey, SecurityAlgorithms.RsaSha1Signature, SecurityAlgorithms.Sha1Digest, new SecurityKeyIdentifier(new X509ThumbprintKeyIdentifierClause(certificate2))); } }
public void DefaultValues() { DateTime d1 = DateTime.UtcNow, d2; SamlAssertion a = new SamlAssertion(); d2 = DateTime.UtcNow; Assert.IsNull(a.Advice, "#1"); Assert.IsNotNull(a.AssertionId, "#2"); Assert.IsTrue(d1 <= a.IssueInstant && a.IssueInstant <= d2, "#3"); Assert.IsNull(a.Issuer, "#4"); Assert.AreEqual(1, a.MajorVersion, "#5"); Assert.AreEqual(1, a.MinorVersion, "#6"); Assert.IsNull(a.SigningCredentials, "#7"); Assert.IsNull(a.SigningToken, "#8"); }
public string GetSaml11Token() { var claimSets = new List <ClaimSet>(ServiceSecurityContext.Current.AuthorizationContext.ClaimSets); ClaimSet claimSet = claimSets.Find((Predicate <ClaimSet>) delegate(ClaimSet target) { WindowsClaimSet defaultClaimSet = target.Issuer as WindowsClaimSet; return(defaultClaimSet != null); }); var accessControlClaims = claimSet.FindClaims(ClaimTypes.Sid, Rights.PossessProperty); SamlAssertion assertion = Saml11Helper.CreateSamlAssertionFromUserNameClaims(accessControlClaims); SamlSecurityToken token = new SamlSecurityToken(assertion); return(Saml11Helper.SerializeSamlToken(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)); }
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); }
public void CompareSamlAssertions() { TestUtilities.WriteHeader($"{this}.CompareSamlAssertions", true); var context = new CompareContext($"{this}.CompareSamlAssertions"); var samlAssertion1 = new SamlAssertion(Guid.NewGuid().ToString(), Default.Issuer, DateTime.Parse(Default.IssueInstantString), null, new SamlAdvice(), new List <SamlStatement> { new SamlAttributeStatement(new SamlSubject(), new List <SamlAttribute> { new SamlAttribute("1", "2", "3") }) }); var samlAssertion2 = new SamlAssertion(Guid.NewGuid().ToString(), Default.Issuer, DateTime.Parse(Default.IssueInstantString), null, new SamlAdvice(), new List <SamlStatement> { new SamlAttributeStatement(new SamlSubject(), new List <SamlAttribute> { new SamlAttribute("1", "2", "3") }) }); IdentityComparer.AreEqual(samlAssertion1, samlAssertion2, context); Assert.True(context.Diffs.Count(s => s == "AssertionId:") == 1); }
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); }
/// <summary> /// Creates an instance of <see cref="SamlSecurityKeyIdentifierClause"/> /// </summary> /// <param name="assertion">The assertion can be queried to obtain information about /// the issuer when resolving the key needed to check the signature. The assertion will /// be read completely when this clause is passed to the SecurityTokenResolver.</param> public SamlSecurityKeyIdentifierClause(SamlAssertion assertion) : base(typeof(SamlSecurityKeyIdentifierClause).ToString()) { this.assertion = assertion; }