/// <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; }
protected void Initialize(SamlAssertion assertion) { if (assertion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("assertion"); } this.assertion = assertion; this.assertion.MakeReadOnly(); }
/// <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); }
protected void Initialize(SamlAssertion assertion) { if (assertion == null) { throw /*System.ServiceModel.*/ DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("assertion"); } _assertion = assertion; }
public virtual SamlAssertion LoadAssertion(XmlDictionaryReader reader, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver) { if (reader == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); SamlAssertion assertion = new SamlAssertion(); assertion.ReadXml(reader, this, keyInfoSerializer, outOfBandTokenResolver); return assertion; }
public virtual SamlAssertion LoadAssertion(XmlDictionaryReader reader, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } SamlAssertion assertion = new SamlAssertion(); assertion.ReadXml(reader, this, keyInfoSerializer, outOfBandTokenResolver); return(assertion); }
public virtual void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader")); } if (samlSerializer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer")); } #pragma warning suppress 56506 // samlSerializer.DictionaryManager is never null. SamlDictionary dictionary = samlSerializer.DictionaryManager.SamlDictionary; // SAML Advice is an optional element and all its child elements are optional // too. So we may have an empty saml:Advice element in the saml token. if (reader.IsEmptyElement) { // Just issue a read for the empty element. reader.MoveToContent(); reader.Read(); return; } reader.MoveToContent(); reader.Read(); while (reader.IsStartElement()) { if (reader.IsStartElement(dictionary.AssertionIdReference, dictionary.Namespace)) { reader.MoveToContent(); this.assertionIdReferences.Add(reader.ReadString()); reader.MoveToContent(); reader.ReadEndElement(); } else if (reader.IsStartElement(dictionary.Assertion, dictionary.Namespace)) { SamlAssertion assertion = new SamlAssertion(); assertion.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver); this.assertions.Add(assertion); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLBadSchema, dictionary.Advice.Value))); } } reader.MoveToContent(); reader.ReadEndElement(); }
/// <summary> /// Retrieves the Authentication Statement from a SAML Assertion. /// </summary> /// <param name="assertion">the SAML Assertion to be parsed</param> /// <returns> /// the Authentication Statement for this Assertion if one exists; otherwise returns null. /// </returns> public static SamlAuthenticationStatement GetSAMLAuthenticationStatement(SamlAssertion assertion) { IEnumerable<SamlStatement> samlStmtEnum = assertion.Statements; Type targetTypeAuth = typeof(System.IdentityModel.Tokens.SamlAuthenticationStatement); int stmtCount=0; foreach (Object obj in samlStmtEnum) { stmtCount++; SamlStatement nextStmt = (SamlStatement) obj; if (nextStmt.GetType().Equals(targetTypeAuth)) { return (SamlAuthenticationStatement)nextStmt; } } return null; }
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 virtual SamlSecurityToken ReadToken(XmlReader reader, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } WrappedReader reader3 = new WrappedReader(XmlDictionaryReader.CreateDictionaryReader(reader)); SamlAssertion assertion = this.LoadAssertion(reader3, keyInfoSerializer, outOfBandTokenResolver); if (assertion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLUnableToLoadAssertion"))); } return(new SamlSecurityToken(assertion)); }
public virtual void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver resolver) { if (reader == null) { throw new ArgumentNullException("reader"); } if (samlSerializer == null) { throw new ArgumentNullException("samlSerializer"); } references.Clear(); assertions.Clear(); reader.ReadStartElement("Evidence", SamlConstants.Namespace); for (reader.MoveToContent(); reader.NodeType == XmlNodeType.Element; reader.MoveToContent()) { if (reader.NamespaceURI != SamlConstants.Namespace) { throw new SecurityTokenException(String.Format("Invalid SAML Evidence element: element '{0}' in namespace '{1}' is unexpected.", reader.LocalName, reader.NamespaceURI)); } switch (reader.LocalName) { case "Assertion": SamlAssertion a = new SamlAssertion(); a.ReadXml(reader, samlSerializer, keyInfoSerializer, resolver); assertions.Add(a); break; case "AssertionIDReference": references.Add(reader.ReadElementContentAsString()); break; default: throw new SecurityTokenException(String.Format("Invalid SAML Evidence element: SAML element '{0}' is unexpected.", reader.LocalName)); } } reader.ReadEndElement(); if (references.Count == 0 && assertions.Count == 0) { throw new SecurityTokenException("At least either one of AssertionIDReference or Assertion must exist in SAML Evidence."); } }
public virtual void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader")); } if (samlSerializer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer")); } SamlDictionary samlDictionary = samlSerializer.DictionaryManager.SamlDictionary; if (reader.IsEmptyElement) { reader.MoveToContent(); reader.Read(); } else { reader.MoveToContent(); reader.Read(); while (reader.IsStartElement()) { if (!reader.IsStartElement(samlDictionary.AssertionIdReference, samlDictionary.Namespace)) { if (!reader.IsStartElement(samlDictionary.Assertion, samlDictionary.Namespace)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLBadSchema", new object[] { samlDictionary.Advice.Value }))); } SamlAssertion item = new SamlAssertion(); item.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver); this.assertions.Add(item); } else { reader.MoveToContent(); this.assertionIdReferences.Add(reader.ReadString()); reader.MoveToContent(); reader.ReadEndElement(); continue; } } reader.MoveToContent(); reader.ReadEndElement(); } }
public virtual void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader")); } if (samlSerializer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer")); } #pragma warning suppress 56506 // samlSerializer.DictionaryManager is never null. SamlDictionary dictionary = samlSerializer.DictionaryManager.SamlDictionary; reader.MoveToContent(); reader.Read(); while (reader.IsStartElement()) { if (reader.IsStartElement(dictionary.AssertionIdReference, dictionary.Namespace)) { reader.MoveToContent(); this.assertionIdReferences.Add(reader.ReadString()); reader.ReadEndElement(); } else if (reader.IsStartElement(dictionary.Assertion, dictionary.Namespace)) { SamlAssertion assertion = new SamlAssertion(); assertion.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver); this.assertions.Add(assertion); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLBadSchema, dictionary.Evidence.Value))); } } if ((this.assertionIdReferences.Count == 0) && (this.assertions.Count == 0)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLEvidenceShouldHaveOneAssertionOnRead))); } reader.MoveToContent(); reader.ReadEndElement(); }
public virtual SamlSecurityToken ReadToken(XmlReader reader, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } XmlDictionaryReader dictionaryReader = XmlDictionaryReader.CreateDictionaryReader(reader); WrappedReader wrappedReader = new WrappedReader(dictionaryReader); SamlAssertion assertion = LoadAssertion(wrappedReader, keyInfoSerializer, outOfBandTokenResolver); if (assertion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLUnableToLoadAssertion))); } //if (assertion.Signature == null) // throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SamlTokenMissingSignature))); return(new SamlSecurityToken(assertion)); }
/// <summary> /// Populates an IList with the Attributes from the SAML Assertion. /// </summary> /// <param name="assertion">the SAML Assertion to be parsed</param> /// <param name="subject">the SAML Subject for which Attributes are to be retrieved</param> /// <returns> /// the IList of matching attributes, which will be an empty List if no matches /// are found /// </returns> public static IList<SamlAttribute> GetAttributesFor(SamlAssertion assertion, SamlSubject subject) { IList<SamlAttribute> attributes = new List<SamlAttribute>(); IEnumerable<SamlStatement> samlStmtEnum = assertion.Statements; Type targetTypeAttr = typeof(System.IdentityModel.Tokens.SamlAttributeStatement); foreach (Object obj in samlStmtEnum) { SamlStatement nextStmt = (SamlStatement) obj; if (nextStmt.GetType().Equals(targetTypeAttr)) { SamlAttributeStatement attributeStatement = (SamlAttributeStatement)nextStmt; if (!(subject.Equals(attributeStatement.SamlSubject) || subject.Name.Equals(attributeStatement.SamlSubject.Name))) { continue; } // Found attributes for this Subject. Transfer them to List. foreach (SamlAttribute nextAttr in attributeStatement.Attributes) { attributes.Add(nextAttr); } } } return attributes; }
/// <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; // Create the Saml condition with allowed audience Uris SamlConditions conditions = new SamlConditions(issueInstant, issueInstant + new TimeSpan(10, 0, 0)); conditions.Conditions.Add(new SamlAudienceRestrictionCondition(new Uri[] { new Uri("http://localhost:8000/servicemodelsamples/service/calc/symm"), new Uri("http://localhost:8000/servicemodelsamples/service/calc/asymm") })); SamlAssertion samlAssertion = new SamlAssertion("_" + Guid.NewGuid().ToString(), "Self", issueInstant, conditions, new SamlAdvice(), samlSubjectStatements ); // Set the SigningCredentials for the SamlAssertion samlAssertion.SigningCredentials = signingCredentials; // Return the SamlAssertion return samlAssertion; }
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 ()); }
/// <summary> /// Constructor /// </summary> /// <param name="assertion">The SAML assertion that the SamlSecurityTokenProvider returns as a SecurityToken</param> /// <param name="proofToken">The proof token associated with the SAML assertion</param> public SamlSecurityTokenProvider(SamlAssertion assertion, SecurityToken proofToken ) { this.assertion = assertion; this.proofToken = proofToken; }
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> /// Read saml:Assertion element from the given reader. /// </summary> /// <param name="reader">XmlReader to deserialize the Assertion from.</param> /// <returns>SamlAssertion</returns> /// <exception cref="ArgumentNullException">The parameter 'reader' is null.</exception> /// <exception cref="XmlException">The XmlReader is not positioned at a saml:Assertion element or the Assertion /// contains unknown child elements.</exception> protected virtual SamlAssertion ReadAssertion(XmlReader reader) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } if (this.Configuration == null) { throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4274)); } if (this.Configuration.IssuerTokenResolver == null) { throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4275)); } SamlAssertion assertion = new SamlAssertion(); EnvelopedSignatureReader wrappedReader = new EnvelopedSignatureReader(reader, new WrappedSerializer(this, assertion), this.Configuration.IssuerTokenResolver, false, true, false); if (!wrappedReader.IsStartElement(SamlConstants.ElementNames.Assertion, SamlConstants.Namespace)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4065, SamlConstants.ElementNames.Assertion, SamlConstants.Namespace, wrappedReader.LocalName, wrappedReader.NamespaceURI))); } string attributeValue = wrappedReader.GetAttribute(SamlConstants.AttributeNames.MajorVersion, null); if (string.IsNullOrEmpty(attributeValue)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4075, SamlConstants.AttributeNames.MajorVersion))); } int majorVersion = XmlConvert.ToInt32(attributeValue); attributeValue = wrappedReader.GetAttribute(SamlConstants.AttributeNames.MinorVersion, null); if (string.IsNullOrEmpty(attributeValue)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4075, SamlConstants.AttributeNames.MinorVersion))); } int minorVersion = XmlConvert.ToInt32(attributeValue); if ((majorVersion != SamlConstants.MajorVersionValue) || (minorVersion != SamlConstants.MinorVersionValue)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4076, majorVersion, minorVersion, SamlConstants.MajorVersionValue, SamlConstants.MinorVersionValue))); } attributeValue = wrappedReader.GetAttribute(SamlConstants.AttributeNames.AssertionId, null); if (string.IsNullOrEmpty(attributeValue)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4075, SamlConstants.AttributeNames.AssertionId))); } if (!XmlUtil.IsValidXmlIDValue(attributeValue)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4077, attributeValue))); } assertion.AssertionId = attributeValue; attributeValue = wrappedReader.GetAttribute(SamlConstants.AttributeNames.Issuer, null); if (string.IsNullOrEmpty(attributeValue)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4075, SamlConstants.AttributeNames.Issuer))); } assertion.Issuer = attributeValue; attributeValue = wrappedReader.GetAttribute(SamlConstants.AttributeNames.IssueInstant, null); if (!string.IsNullOrEmpty(attributeValue)) { assertion.IssueInstant = DateTime.ParseExact( attributeValue, DateTimeFormats.Accepted, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None).ToUniversalTime(); } wrappedReader.MoveToContent(); wrappedReader.Read(); if (wrappedReader.IsStartElement(SamlConstants.ElementNames.Conditions, SamlConstants.Namespace)) { assertion.Conditions = ReadConditions(wrappedReader); } if (wrappedReader.IsStartElement(SamlConstants.ElementNames.Advice, SamlConstants.Namespace)) { assertion.Advice = ReadAdvice(wrappedReader); } while (wrappedReader.IsStartElement()) { assertion.Statements.Add(ReadStatement(wrappedReader)); } if (assertion.Statements.Count == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.ID4078))); } wrappedReader.MoveToContent(); wrappedReader.ReadEndElement(); // Reading the end element will complete the signature; // capture the signing creds assertion.SigningCredentials = wrappedReader.SigningCredentials; // Save the captured on-the-wire data, which can then be used // to re-emit this assertion, preserving the same signature. assertion.CaptureSourceData(wrappedReader); return assertion; }
public virtual void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader")); } if (samlSerializer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer")); } SamlDictionary samlDictionary = samlSerializer.DictionaryManager.SamlDictionary; reader.MoveToContent(); reader.Read(); while (reader.IsStartElement()) { if (!reader.IsStartElement(samlDictionary.AssertionIdReference, samlDictionary.Namespace)) { if (!reader.IsStartElement(samlDictionary.Assertion, samlDictionary.Namespace)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLBadSchema", new object[] { samlDictionary.Evidence.Value }))); } SamlAssertion item = new SamlAssertion(); item.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver); this.assertions.Add(item); } else { reader.MoveToContent(); this.assertionIdReferences.Add(reader.ReadString()); reader.ReadEndElement(); continue; } } if ((this.assertionIdReferences.Count == 0) && (this.assertions.Count == 0)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLEvidenceShouldHaveOneAssertionOnRead"))); } reader.MoveToContent(); reader.ReadEndElement(); }
public SamlSecurityToken(SamlAssertion assertion) { this.assertion = assertion; Initialize(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; }
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 ("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 void WriteXmlNoStatement () { SamlAssertion a = new SamlAssertion (); a.Issuer = "my_boss"; using (XmlDictionaryWriter dw = CreateWriter (new StringWriter ())) { a.WriteXml (dw, null, null); } }
protected void Initialize(SamlAssertion assertion) { throw new NotImplementedException(); }
public virtual void ReadXml (XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoTokenSerializer, SecurityTokenResolver outOfBandTokenResolver) { if (reader == null) throw new ArgumentNullException ("reader"); if (samlSerializer == null) throw new ArgumentNullException ("samlSerializer"); reader.ReadStartElement ("Advice", SamlConstants.Namespace); for (reader.MoveToContent (); reader.NodeType == XmlNodeType.Element; reader.MoveToContent ()) { if (reader.NamespaceURI != SamlConstants.Namespace) throw new SecurityTokenException (String.Format ("Invalid SAML Advice element: element '{0}' in namespace '{1}' is unexpected.", reader.LocalName, reader.NamespaceURI)); switch (reader.LocalName) { case "Assertion": SamlAssertion a = new SamlAssertion (); a.ReadXml (reader, samlSerializer, keyInfoTokenSerializer, outOfBandTokenResolver); assertions.Add (a); break; case "AssertionIDReference": idrefs.Add (reader.ReadElementContentAsString ()); break; default: throw new SecurityTokenException (String.Format ("Invalid SAML Advice element: SAML element '{0}' is unexpected.", reader.LocalName)); } } reader.ReadEndElement (); }
/// <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 SamlSecurityToken(SamlAssertion assertion) { Initialize(assertion); }
/// <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 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); } }
public virtual void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver) { if (reader == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader")); if (samlSerializer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer")); #pragma warning suppress 56506 // samlSerializer.DictionaryManager is never null. SamlDictionary dictionary = samlSerializer.DictionaryManager.SamlDictionary; reader.MoveToContent(); reader.Read(); while (reader.IsStartElement()) { if (reader.IsStartElement(dictionary.AssertionIdReference, dictionary.Namespace)) { reader.MoveToContent(); this.assertionIdReferences.Add(reader.ReadString()); reader.ReadEndElement(); } else if (reader.IsStartElement(dictionary.Assertion, dictionary.Namespace)) { SamlAssertion assertion = new SamlAssertion(); assertion.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver); this.assertions.Add(assertion); } else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLBadSchema, dictionary.Evidence.Value))); } if ((this.assertionIdReferences.Count == 0) && (this.assertions.Count == 0)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLEvidenceShouldHaveOneAssertionOnRead))); reader.MoveToContent(); reader.ReadEndElement(); }
/// <summary> /// Serializes a given SamlAssertion to the XmlWriter. /// </summary> /// <param name="writer">XmlWriter to use for the serialization.</param> /// <param name="assertion">Assertion to be serialized into the XmlWriter.</param> /// <exception cref="ArgumentNullException">The input parameter 'writer' or 'assertion' is null.</exception> protected virtual void WriteAssertion(XmlWriter writer, SamlAssertion assertion) { if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer"); } if (assertion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("assertion"); } SamlAssertion SamlAssertion = assertion as SamlAssertion; if (SamlAssertion != null) { if (SamlAssertion.CanWriteSourceData) { SamlAssertion.WriteSourceData(writer); return; } } if (assertion.SigningCredentials != null) { writer = new EnvelopedSignatureWriter(writer, assertion.SigningCredentials, assertion.AssertionId, new WrappedSerializer(this, assertion)); } writer.WriteStartElement(SamlConstants.Prefix, SamlConstants.ElementNames.Assertion, SamlConstants.Namespace); writer.WriteAttributeString(SamlConstants.AttributeNames.MajorVersion, null, Convert.ToString(SamlConstants.MajorVersionValue, CultureInfo.InvariantCulture)); writer.WriteAttributeString(SamlConstants.AttributeNames.MinorVersion, null, Convert.ToString(SamlConstants.MinorVersionValue, CultureInfo.InvariantCulture)); writer.WriteAttributeString(SamlConstants.AttributeNames.AssertionId, null, assertion.AssertionId); writer.WriteAttributeString(SamlConstants.AttributeNames.Issuer, null, assertion.Issuer); writer.WriteAttributeString(SamlConstants.AttributeNames.IssueInstant, null, assertion.IssueInstant.ToUniversalTime().ToString(DateTimeFormats.Generated, CultureInfo.InvariantCulture)); // Write out conditions if (assertion.Conditions != null) { WriteConditions(writer, assertion.Conditions); } // Write out advice if there is one if (assertion.Advice != null) { WriteAdvice(writer, assertion.Advice); } // Write statements. for (int i = 0; i < assertion.Statements.Count; i++) { WriteStatement(writer, assertion.Statements[i]); } writer.WriteEndElement(); }
public virtual void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver) { if (reader == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader")); if (samlSerializer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer")); #pragma warning suppress 56506 // samlSerializer.DictionaryManager is never null. SamlDictionary dictionary = samlSerializer.DictionaryManager.SamlDictionary; // SAML Advice is an optional element and all its child elements are optional // too. So we may have an empty saml:Advice element in the saml token. if (reader.IsEmptyElement) { // Just issue a read for the empty element. reader.MoveToContent(); reader.Read(); return; } reader.MoveToContent(); reader.Read(); while (reader.IsStartElement()) { if (reader.IsStartElement(dictionary.AssertionIdReference, dictionary.Namespace)) { reader.MoveToContent(); this.assertionIdReferences.Add(reader.ReadString()); reader.MoveToContent(); reader.ReadEndElement(); } else if (reader.IsStartElement(dictionary.Assertion, dictionary.Namespace)) { SamlAssertion assertion = new SamlAssertion(); assertion.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver); this.assertions.Add(assertion); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLBadSchema, dictionary.Advice.Value))); } } reader.MoveToContent(); reader.ReadEndElement(); }
/// <summary> /// Creates a SAML token for the specified email address. /// </summary> public static UserIdentity CreateSAMLToken(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.Windows; userid.StorePath = "LocalMachine\\My"; userid.SubjectName = "UA Sample Client"; X509Certificate2 certificate = 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>())); return new UserIdentity(new SamlSecurityToken(assertion)); }
/// <summary> /// Resolves the Signing Key Identifier to a SecurityToken. /// </summary> /// <param name="assertion">The Assertion for which the Issuer token is to be resolved.</param> /// <param name="issuerResolver">The current SecurityTokenResolver associated with this handler.</param> /// <returns>Instance of SecurityToken</returns> /// <exception cref="ArgumentNullException">Input parameter 'assertion' is null.</exception> /// <exception cref="ArgumentNullException">Input parameter 'issuerResolver' is null.</exception>/// /// <exception cref="SecurityTokenException">Unable to resolve token.</exception> protected virtual SecurityToken ResolveIssuerToken(SamlAssertion assertion, SecurityTokenResolver issuerResolver) { if (null == assertion) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("assertion"); } if (null == issuerResolver) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("issuerResolver"); } SecurityToken token; if (TryResolveIssuerToken(assertion, issuerResolver, out token)) { return token; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.ID4220))); } }
/// <summary> /// Determines whether the SAML Assertion is valid in terms of the 'not before' and the /// 'not on or after' times. /// </summary> /// <param name="assertion">the SAML Assertion to be checked</param> /// <param name="toleranceTicks"> /// Tolerance ticks for checking the current time against the SAML Assertion valid times. /// </param> /// <returns> /// true if this Assertion is valid relative to the current time; otherwise returns false /// </returns> public static bool IsValidAssertion(SamlAssertion assertion, long toleranceTicks) { DateTime notBefore = assertion.Conditions.NotBefore; DateTime notOnOrAfter = assertion.Conditions.NotOnOrAfter; return IsValidAssertion(notBefore, notOnOrAfter, toleranceTicks); }
/// <summary> /// Resolves the Signing Key Identifier to a SecurityToken. /// </summary> /// <param name="assertion">The Assertion for which the Issuer token is to be resolved.</param> /// <param name="issuerResolver">The current SecurityTokenResolver associated with this handler.</param> /// <param name="token">Resolved token.</param> /// <returns>True if token is resolved.</returns> /// <exception cref="ArgumentNullException">Input parameter 'assertion' is null.</exception> protected virtual bool TryResolveIssuerToken(SamlAssertion assertion, SecurityTokenResolver issuerResolver, out SecurityToken token) { if (null == assertion) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("assertion"); } if (assertion.SigningCredentials != null && assertion.SigningCredentials.SigningKeyIdentifier != null && issuerResolver != null) { SecurityKeyIdentifier keyIdentifier = assertion.SigningCredentials.SigningKeyIdentifier; return issuerResolver.TryResolveToken(keyIdentifier, out token); } else { token = null; return false; } }
/// <summary> /// Reads the ds:KeyInfo element inside the Saml Signature. /// </summary> /// <param name="reader">An XmlReader that can be positioned at a ds:KeyInfo element.</param> /// <param name="assertion">The assertion that is having the signature checked.</param> /// <returns>The <see cref="SecurityKeyIdentifier"/> that defines the key to use to check the signature.</returns> /// <exception cref="ArgumentNullException">The input parameter 'reader' is null.</exception> /// <exception cref="InvalidOperationException">Unable to read the KeyIdentifier from the XmlReader.</exception> /// <remarks>If the reader is not positioned at a ds:KeyInfo element, the <see cref="SecurityKeyIdentifier"/> returned will /// contain a single <see cref="SecurityKeyIdentifierClause"/> of type <see cref="EmptySecurityKeyIdentifierClause"/></remarks> protected virtual SecurityKeyIdentifier ReadSigningKeyInfo(XmlReader reader, SamlAssertion assertion) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } SecurityKeyIdentifier ski; if (KeyInfoSerializer.CanReadKeyIdentifier(reader)) { ski = KeyInfoSerializer.ReadKeyIdentifier(reader); } else { KeyInfo keyInfo = new KeyInfo(KeyInfoSerializer); keyInfo.ReadXml(XmlDictionaryReader.CreateDictionaryReader(reader)); ski = keyInfo.KeyIdentifier; } // no key info if (ski.Count == 0) { return new SecurityKeyIdentifier(new SamlSecurityKeyIdentifierClause(assertion)); } return ski; }
public WrappedSerializer(SamlSecurityTokenHandler parent, SamlAssertion assertion) { if (parent == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parent"); } _parent = parent; _assertion = assertion; }
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 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. An attribute statement is based on // a subject statement and SAML attributes that result 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); return new SamlSecurityToken(assertion); }
public void WriteXmlNullIssuer () { SamlAssertion a = new SamlAssertion (); using (XmlDictionaryWriter dw = CreateWriter (new StringWriter ())) { a.WriteXml (dw, null, null); } }