Exemple #1
0
		public void NotBefore ()
		{
			SamlConditions c = new SamlConditions ();
			DateTime min = DateTime.SpecifyKind (DateTime.MinValue, DateTimeKind.Utc);
			c.NotBefore = min;
			Assert.AreEqual (min, c.NotBefore, "#1");
		}
Exemple #2
0
		public SamlAssertion (string assertionId, string issuer,
			DateTime issueInstant, SamlConditions conditions,
			SamlAdvice advice, IEnumerable<SamlStatement> statements)
		{
			if (IsInvalidAssertionId (assertionId))
				throw new ArgumentException (String.Format ("The assertionId '{0}' must be a valid XML NCName.", assertionId));

			if (issuer == null || issuer.Length == 0)
				throw new ArgumentException ("issuer");
			if (statements == null)
				throw new ArgumentNullException ("statements");

			major = 1;
			minor = 1;

			assertion_id = assertionId;
			this.issuer = issuer;
			issue_instant = issueInstant;
			this.conditions = conditions;
			this.advice = advice;
			foreach (SamlStatement s in statements) {
				if (s == null)
					throw new ArgumentException ("statements contain null item.");
				this.statements.Add (s);
			}
			if (this.statements.Count == 0)
				throw new ArgumentException ("At least one assertion statement is required.");
		}
Exemple #3
0
		public void NotOnOrAfter ()
		{
			SamlConditions c = new SamlConditions ();
			DateTime max = DateTime.SpecifyKind (DateTime.MaxValue, DateTimeKind.Utc);
			c.NotOnOrAfter = max;
			Assert.AreEqual (max, c.NotOnOrAfter, "#1");
		}
Exemple #4
0
		public void WriteXml1 ()
		{
			SamlConditions c = new SamlConditions ();
			StringWriter sw = new StringWriter ();
			using (XmlDictionaryWriter dw = CreateWriter (sw)) {
				c.WriteXml (dw, new SamlSerializer (), null);
			}
			Assert.AreEqual (String.Format ("<?xml version=\"1.0\" encoding=\"utf-16\"?><saml:Conditions xmlns:saml=\"{0}\" />", SamlConstants.Namespace), 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);
		}
 public virtual SamlConditions LoadConditions(XmlDictionaryReader reader, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
 {
     if (reader == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
     }
     SamlConditions conditions = new SamlConditions();
     conditions.ReadXml(reader, this, keyInfoSerializer, outOfBandTokenResolver);
     return conditions;
 }
        public virtual SamlConditions LoadConditions(XmlDictionaryReader reader, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }
            SamlConditions conditions = new SamlConditions();

            conditions.ReadXml(reader, this, keyInfoSerializer, outOfBandTokenResolver);
            return(conditions);
        }
Exemple #8
0
        public SamlAssertion(
            string assertionId,
            string issuer,
            DateTime issueInstant,
            SamlConditions samlConditions,
            SamlAdvice samlAdvice,
            IEnumerable <SamlStatement> samlStatements
            )
        {
            if (string.IsNullOrEmpty(assertionId))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLAssertionIdRequired));
            }

            if (!IsAssertionIdValid(assertionId))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLAssertionIDIsInvalid, assertionId));
            }

            if (string.IsNullOrEmpty(issuer))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLAssertionIssuerRequired));
            }

            if (samlStatements == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("samlStatements");
            }

            this.assertionId  = assertionId;
            this.issuer       = issuer;
            this.issueInstant = issueInstant.ToUniversalTime();
            this.conditions   = samlConditions;
            this.advice       = samlAdvice;

            foreach (SamlStatement samlStatement in samlStatements)
            {
                if (samlStatement == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLEntityCannotBeNullOrEmpty, XD.SamlDictionary.Statement.Value));
                }

                this.statements.Add(samlStatement);
            }

            if (this.statements.Count == 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLAssertionRequireOneStatement));
            }
        }
        public SamlAssertion(
            string assertionId,
            string issuer,
            DateTime issueInstant,
            SamlConditions samlConditions,
            SamlAdvice samlAdvice,
            IEnumerable<SamlStatement> samlStatements
            )
        {
            if (string.IsNullOrEmpty(assertionId))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLAssertionIdRequired));

            if (!IsAssertionIdValid(assertionId))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLAssertionIDIsInvalid, assertionId));

            if (string.IsNullOrEmpty(issuer))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLAssertionIssuerRequired));

            if (samlStatements == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("samlStatements");
            }

            this.assertionId = assertionId;
            this.issuer = issuer;
            this.issueInstant = issueInstant.ToUniversalTime();
            this.conditions = samlConditions;
            this.advice = samlAdvice;

            foreach (SamlStatement samlStatement in samlStatements)
            {
                if (samlStatement == null)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLEntityCannotBeNullOrEmpty, XD.SamlDictionary.Statement.Value));

                this.statements.Add(samlStatement);
            }

            if (this.statements.Count == 0)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLAssertionRequireOneStatement));
        }
 public SamlAssertion(string assertionId, string issuer, DateTime issueInstant, SamlConditions samlConditions, SamlAdvice samlAdvice, IEnumerable<SamlStatement> samlStatements)
 {
     this.assertionId = "SamlSecurityToken-" + Guid.NewGuid().ToString();
     this.issueInstant = DateTime.UtcNow.ToUniversalTime();
     this.statements = new ImmutableCollection<SamlStatement>();
     if (string.IsNullOrEmpty(assertionId))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.IdentityModel.SR.GetString("SAMLAssertionIdRequired"));
     }
     if (!this.IsAssertionIdValid(assertionId))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.IdentityModel.SR.GetString("SAMLAssertionIDIsInvalid", new object[] { assertionId }));
     }
     if (string.IsNullOrEmpty(issuer))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.IdentityModel.SR.GetString("SAMLAssertionIssuerRequired"));
     }
     if (samlStatements == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("samlStatements");
     }
     this.assertionId = assertionId;
     this.issuer = issuer;
     this.issueInstant = issueInstant.ToUniversalTime();
     this.conditions = samlConditions;
     this.advice = samlAdvice;
     foreach (SamlStatement statement in samlStatements)
     {
         if (statement == null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.IdentityModel.SR.GetString("SAMLEntityCannotBeNullOrEmpty", new object[] { XD.SamlDictionary.Statement.Value }));
         }
         this.statements.Add(statement);
     }
     if (this.statements.Count == 0)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.IdentityModel.SR.GetString("SAMLAssertionRequireOneStatement"));
     }
 }
 public SamlAssertion(string assertionId, string issuer, DateTime issueInstant, SamlConditions samlConditions, SamlAdvice samlAdvice, IEnumerable <SamlStatement> samlStatements)
 {
     this.assertionId  = "SamlSecurityToken-" + Guid.NewGuid().ToString();
     this.issueInstant = DateTime.UtcNow.ToUniversalTime();
     this.statements   = new ImmutableCollection <SamlStatement>();
     if (string.IsNullOrEmpty(assertionId))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.IdentityModel.SR.GetString("SAMLAssertionIdRequired"));
     }
     if (!this.IsAssertionIdValid(assertionId))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.IdentityModel.SR.GetString("SAMLAssertionIDIsInvalid", new object[] { assertionId }));
     }
     if (string.IsNullOrEmpty(issuer))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.IdentityModel.SR.GetString("SAMLAssertionIssuerRequired"));
     }
     if (samlStatements == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("samlStatements");
     }
     this.assertionId  = assertionId;
     this.issuer       = issuer;
     this.issueInstant = issueInstant.ToUniversalTime();
     this.conditions   = samlConditions;
     this.advice       = samlAdvice;
     foreach (SamlStatement statement in samlStatements)
     {
         if (statement == null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.IdentityModel.SR.GetString("SAMLEntityCannotBeNullOrEmpty", new object[] { XD.SamlDictionary.Statement.Value }));
         }
         this.statements.Add(statement);
     }
     if (this.statements.Count == 0)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.IdentityModel.SR.GetString("SAMLAssertionRequireOneStatement"));
     }
 }
Exemple #12
0
        public SamlAssertion(string assertionId, string issuer,
                             DateTime issueInstant, SamlConditions conditions,
                             SamlAdvice advice, IEnumerable <SamlStatement> statements)
        {
            if (IsInvalidAssertionId(assertionId))
            {
                throw new ArgumentException(String.Format("The assertionId '{0}' must be a valid XML NCName.", assertionId));
            }

            if (issuer == null || issuer.Length == 0)
            {
                throw new ArgumentException("issuer");
            }
            if (statements == null)
            {
                throw new ArgumentNullException("statements");
            }

            major = 1;
            minor = 1;

            assertion_id    = assertionId;
            this.issuer     = issuer;
            issue_instant   = issueInstant;
            this.conditions = conditions;
            this.advice     = advice;
            foreach (SamlStatement s in statements)
            {
                if (s == null)
                {
                    throw new ArgumentException("statements contain null item.");
                }
                this.statements.Add(s);
            }
            if (this.statements.Count == 0)
            {
                throw new ArgumentException("At least one assertion statement is required.");
            }
        }
        /// <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;
        }
Exemple #14
0
        public virtual void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("ReadXml"));
            }

            if (samlSerializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));
            }

            XmlDictionaryReader dictionaryReader = XmlDictionaryReader.CreateDictionaryReader(reader);
            WrappedReader       wrappedReader    = new WrappedReader(dictionaryReader);

#pragma warning suppress 56506 // samlSerializer.DictionaryManager is never null.
            SamlDictionary dictionary = samlSerializer.DictionaryManager.SamlDictionary;

            if (!wrappedReader.IsStartElement(dictionary.Assertion, dictionary.Namespace))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLElementNotRecognized, wrappedReader.LocalName)));
            }

            string attributeValue = wrappedReader.GetAttribute(dictionary.MajorVersion, null);
            if (string.IsNullOrEmpty(attributeValue))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAssertionMissingMajorVersionAttributeOnRead)));
            }
            int majorVersion = Int32.Parse(attributeValue, CultureInfo.InvariantCulture);

            attributeValue = wrappedReader.GetAttribute(dictionary.MinorVersion, null);
            if (string.IsNullOrEmpty(attributeValue))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAssertionMissingMinorVersionAttributeOnRead)));
            }

            int minorVersion = Int32.Parse(attributeValue, CultureInfo.InvariantCulture);

            if ((majorVersion != SamlConstants.MajorVersionValue) || (minorVersion != SamlConstants.MinorVersionValue))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLTokenVersionNotSupported, majorVersion, minorVersion, SamlConstants.MajorVersionValue, SamlConstants.MinorVersionValue)));
            }

            attributeValue = wrappedReader.GetAttribute(dictionary.AssertionId, null);
            if (string.IsNullOrEmpty(attributeValue))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAssertionIdRequired)));
            }

            if (!IsAssertionIdValid(attributeValue))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAssertionIDIsInvalid, attributeValue)));
            }

            this.assertionId = attributeValue;

            attributeValue = wrappedReader.GetAttribute(dictionary.Issuer, null);
            if (string.IsNullOrEmpty(attributeValue))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAssertionMissingIssuerAttributeOnRead)));
            }
            this.issuer = attributeValue;

            attributeValue = wrappedReader.GetAttribute(dictionary.IssueInstant, null);
            if (!string.IsNullOrEmpty(attributeValue))
            {
                this.issueInstant = DateTime.ParseExact(
                    attributeValue, SamlConstants.AcceptedDateTimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None).ToUniversalTime();
            }

            wrappedReader.MoveToContent();
            wrappedReader.Read();

            if (wrappedReader.IsStartElement(dictionary.Conditions, dictionary.Namespace))
            {
                this.conditions = samlSerializer.LoadConditions(wrappedReader, keyInfoSerializer, outOfBandTokenResolver);
                if (this.conditions == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLUnableToLoadCondtions)));
                }
            }

            if (wrappedReader.IsStartElement(dictionary.Advice, dictionary.Namespace))
            {
                this.advice = samlSerializer.LoadAdvice(wrappedReader, keyInfoSerializer, outOfBandTokenResolver);
                if (this.advice == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLUnableToLoadAdvice)));
                }
            }

            while (wrappedReader.IsStartElement())
            {
#pragma warning suppress 56506 // samlSerializer.DictionaryManager is never null.
                if (wrappedReader.IsStartElement(samlSerializer.DictionaryManager.XmlSignatureDictionary.Signature, samlSerializer.DictionaryManager.XmlSignatureDictionary.Namespace))
                {
                    break;
                }
                else
                {
                    SamlStatement statement = samlSerializer.LoadStatement(wrappedReader, keyInfoSerializer, outOfBandTokenResolver);
                    if (statement == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLUnableToLoadStatement)));
                    }
                    this.statements.Add(statement);
                }
            }

            if (this.statements.Count == 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAssertionRequireOneStatementOnRead)));
            }

            if (wrappedReader.IsStartElement(samlSerializer.DictionaryManager.XmlSignatureDictionary.Signature, samlSerializer.DictionaryManager.XmlSignatureDictionary.Namespace))
            {
                this.ReadSignature(wrappedReader, keyInfoSerializer, outOfBandTokenResolver, samlSerializer);
            }

            wrappedReader.MoveToContent();
            wrappedReader.ReadEndElement();

            this.tokenStream = wrappedReader.XmlTokens;

            if (this.signature != null)
            {
                VerifySignature(this.signature, this.verificationKey);
            }

            BuildCryptoList();
        }
Exemple #15
0
 /// <summary>
 /// This method adds the audience uri restriction condition to the SAML assetion.
 /// </summary>
 /// <param name="samlConditions">The saml condition collection where the audience uri restriction condition will be added.</param>
 public override void AddAudienceRestrictionCondition(SamlConditions samlConditions)
 {
     samlConditions.Conditions.Add(new SamlAudienceRestrictionCondition(new Uri[] { new Uri(Constants.BookStoreServiceAudienceUri) }));
 }
 public virtual void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
 {
     if (reader == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("ReadXml"));
     }
     if (samlSerializer == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));
     }
     WrappedReader reader3 = new WrappedReader(XmlDictionaryReader.CreateDictionaryReader(reader));
     SamlDictionary samlDictionary = samlSerializer.DictionaryManager.SamlDictionary;
     if (!reader3.IsStartElement(samlDictionary.Assertion, samlDictionary.Namespace))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLElementNotRecognized", new object[] { reader3.LocalName })));
     }
     string attribute = reader3.GetAttribute(samlDictionary.MajorVersion, null);
     if (string.IsNullOrEmpty(attribute))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAssertionMissingMajorVersionAttributeOnRead")));
     }
     int num = int.Parse(attribute, CultureInfo.InvariantCulture);
     attribute = reader3.GetAttribute(samlDictionary.MinorVersion, null);
     if (string.IsNullOrEmpty(attribute))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAssertionMissingMinorVersionAttributeOnRead")));
     }
     int num2 = int.Parse(attribute, CultureInfo.InvariantCulture);
     if ((num != SamlConstants.MajorVersionValue) || (num2 != SamlConstants.MinorVersionValue))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLTokenVersionNotSupported", new object[] { num, num2, SamlConstants.MajorVersionValue, SamlConstants.MinorVersionValue })));
     }
     attribute = reader3.GetAttribute(samlDictionary.AssertionId, null);
     if (string.IsNullOrEmpty(attribute))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAssertionIdRequired")));
     }
     if (!this.IsAssertionIdValid(attribute))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAssertionIDIsInvalid", new object[] { attribute })));
     }
     this.assertionId = attribute;
     attribute = reader3.GetAttribute(samlDictionary.Issuer, null);
     if (string.IsNullOrEmpty(attribute))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAssertionMissingIssuerAttributeOnRead")));
     }
     this.issuer = attribute;
     attribute = reader3.GetAttribute(samlDictionary.IssueInstant, null);
     if (!string.IsNullOrEmpty(attribute))
     {
         this.issueInstant = DateTime.ParseExact(attribute, SamlConstants.AcceptedDateTimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None).ToUniversalTime();
     }
     reader3.MoveToContent();
     reader3.Read();
     if (reader3.IsStartElement(samlDictionary.Conditions, samlDictionary.Namespace))
     {
         this.conditions = samlSerializer.LoadConditions(reader3, keyInfoSerializer, outOfBandTokenResolver);
         if (this.conditions == null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLUnableToLoadCondtions")));
         }
     }
     if (reader3.IsStartElement(samlDictionary.Advice, samlDictionary.Namespace))
     {
         this.advice = samlSerializer.LoadAdvice(reader3, keyInfoSerializer, outOfBandTokenResolver);
         if (this.advice == null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLUnableToLoadAdvice")));
         }
     }
     while (reader3.IsStartElement())
     {
         if (reader3.IsStartElement(samlSerializer.DictionaryManager.XmlSignatureDictionary.Signature, samlSerializer.DictionaryManager.XmlSignatureDictionary.Namespace))
         {
             break;
         }
         SamlStatement item = samlSerializer.LoadStatement(reader3, keyInfoSerializer, outOfBandTokenResolver);
         if (item == null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLUnableToLoadStatement")));
         }
         this.statements.Add(item);
     }
     if (this.statements.Count == 0)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAssertionRequireOneStatementOnRead")));
     }
     if (reader3.IsStartElement(samlSerializer.DictionaryManager.XmlSignatureDictionary.Signature, samlSerializer.DictionaryManager.XmlSignatureDictionary.Namespace))
     {
         this.ReadSignature(reader3, keyInfoSerializer, outOfBandTokenResolver, samlSerializer);
     }
     reader3.MoveToContent();
     reader3.ReadEndElement();
     this.tokenStream = reader3.XmlTokens;
     if (this.signature != null)
     {
         this.VerifySignature(this.signature, this.verificationKey);
     }
     this.BuildCryptoList();
 }
        /// <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);
        }
        /// <summary>
        /// Rejects tokens that are not valid. 
        /// </summary>
        /// <remarks>
        /// The token may be invalid for a number of reasons. For example, the 
        /// current time may not be within the token's validity period, the 
        /// token may contain invalid or contradictory data, or the token 
        /// may contain unsupported SAML elements.
        /// </remarks>
        /// <param name="conditions">SAML condition to be validated.</param>
        /// <param name="enforceAudienceRestriction">True to check for Audience Restriction condition.</param>
        protected virtual void ValidateConditions(SamlConditions conditions, bool enforceAudienceRestriction)
        {
            if (null != conditions)
            {
                DateTime now = DateTime.UtcNow;

                if (null != conditions.NotBefore
                    && DateTimeUtil.Add(now, Configuration.MaxClockSkew) < conditions.NotBefore)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new SecurityTokenNotYetValidException(SR.GetString(SR.ID4222, conditions.NotBefore, now)));
                }

                if (null != conditions.NotOnOrAfter
                    && DateTimeUtil.Add(now, Configuration.MaxClockSkew.Negate()) >= conditions.NotOnOrAfter)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new SecurityTokenExpiredException(SR.GetString(SR.ID4223, conditions.NotOnOrAfter, now)));
                }
            }

            //
            // Enforce the audience restriction
            //
            if (enforceAudienceRestriction)
            {
                if (this.Configuration == null || this.Configuration.AudienceRestriction.AllowedAudienceUris.Count == 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID1032)));
                }

                //
                // Process each condition, enforcing the AudienceRestrictionConditions
                //
                bool foundAudienceRestriction = false;

                if (null != conditions && null != conditions.Conditions)
                {
                    foreach (SamlCondition condition in conditions.Conditions)
                    {
                        SamlAudienceRestrictionCondition audienceRestriction = condition as SamlAudienceRestrictionCondition;
                        if (null == audienceRestriction)
                        {
                            // Skip other conditions
                            continue;
                        }

                        _samlSecurityTokenRequirement.ValidateAudienceRestriction(this.Configuration.AudienceRestriction.AllowedAudienceUris, audienceRestriction.Audiences);
                        foundAudienceRestriction = true;
                    }
                }

                if (!foundAudienceRestriction)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AudienceUriValidationFailedException(SR.GetString(SR.ID1035)));
                }
            }
        }
 /// <summary>
 /// This method adds the audience uri restriction condition to the SAML assetion.
 /// </summary>
 /// <param name="samlConditions">The saml condition collection where the audience uri restriction condition will be added.</param>
 public abstract void AddAudienceRestrictionCondition(SamlConditions samlConditions);
        /// <summary>
        /// Virtual method for ProcessRequestSecurityToken
        /// Should be overridden by STS implementations that derive from this base class
        /// </summary>
        public virtual Message ProcessRequestSecurityToken(Message message)
        {
            // Check for appropriate action header
            EnsureRequestSecurityTokenAction(message);

            // Extract the MessageID from the request message
            UniqueId requestMessageID = message.Headers.MessageId;
            if (requestMessageID == null)
                throw new InvalidOperationException("The request message does not have a message ID.");

            // Get the RST from the message
            RequestSecurityToken rst = RequestSecurityToken.CreateFrom(message.GetReaderAtBodyContents());

            // Set up the claims we are going to issue
            Collection<SamlAttribute> samlAttributes = GetIssuedClaims(rst);

            // get the key size, default to 192
            int keySize = (rst.KeySize != 0) ? rst.KeySize : 192;

            // Create proof token
            // Get requester entropy, if any
            byte[] senderEntropy = null;
            SecurityToken entropyToken = rst.RequestorEntropy;
            if (entropyToken != null)
            {
                senderEntropy = ((BinarySecretSecurityToken)entropyToken).GetKeyBytes();
            }

            byte[] key = null;
            byte[] stsEntropy = null;

            // If sender provided entropy, then use combined entropy
            if (senderEntropy != null)
            {
                // Create an array to store the entropy bytes
                stsEntropy = new byte[keySize / 8];
                // Create some random bytes
                RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();
                random.GetNonZeroBytes(stsEntropy);
                // Compute the combined key
                key = RequestSecurityTokenResponse.ComputeCombinedKey(senderEntropy, stsEntropy, keySize);
            }
            else // Issuer entropy only...
            {
                // Create an array to store the entropy bytes
                key = new byte[keySize / 8];
                // Create some random bytes
                RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();
                random.GetNonZeroBytes(key);
            }

            // Create a BinarySecretSecurityToken to be the proof token, based on the key material
            // in key. The key is the combined key in the combined entropy case, or the issuer entropy
            // otherwise
            BinarySecretSecurityToken proofToken = new BinarySecretSecurityToken(key);

            // Create the saml condition
            SamlConditions samlConditions = new SamlConditions(DateTime.UtcNow - TimeSpan.FromMinutes(5), DateTime.UtcNow + TimeSpan.FromHours(10));
            AddAudienceRestrictionCondition(samlConditions);

            // Create a SAML token, valid for around 10 hours
            SamlSecurityToken samlToken = SamlTokenCreator.CreateSamlToken(this.stsName,
                                                                           proofToken,
                                                                           this.IssuerToken,
                                                                           this.ProofKeyEncryptionToken,
                                                                           samlConditions,
                                                                           samlAttributes);

            // Set up RSTR
            RequestSecurityTokenBase rstr = GetRequestSecurityTokenResponse(rst, keySize, proofToken, samlToken, senderEntropy, stsEntropy);

            // Create a message from the RSTR
            Message rstrMessage = Message.CreateMessage(message.Version, Constants.Trust.Actions.IssueReply, rstr);

            // Set RelatesTo of response message to MessageID of request message
            rstrMessage.Headers.RelatesTo = requestMessageID;

            // Return the create message
            return rstrMessage;
        }
        /// <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();
        }
        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 virtual void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("ReadXml"));
            }
            if (samlSerializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));
            }
            WrappedReader  reader3        = new WrappedReader(XmlDictionaryReader.CreateDictionaryReader(reader));
            SamlDictionary samlDictionary = samlSerializer.DictionaryManager.SamlDictionary;

            if (!reader3.IsStartElement(samlDictionary.Assertion, samlDictionary.Namespace))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLElementNotRecognized", new object[] { reader3.LocalName })));
            }
            string attribute = reader3.GetAttribute(samlDictionary.MajorVersion, null);

            if (string.IsNullOrEmpty(attribute))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAssertionMissingMajorVersionAttributeOnRead")));
            }
            int num = int.Parse(attribute, CultureInfo.InvariantCulture);

            attribute = reader3.GetAttribute(samlDictionary.MinorVersion, null);
            if (string.IsNullOrEmpty(attribute))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAssertionMissingMinorVersionAttributeOnRead")));
            }
            int num2 = int.Parse(attribute, CultureInfo.InvariantCulture);

            if ((num != SamlConstants.MajorVersionValue) || (num2 != SamlConstants.MinorVersionValue))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLTokenVersionNotSupported", new object[] { num, num2, SamlConstants.MajorVersionValue, SamlConstants.MinorVersionValue })));
            }
            attribute = reader3.GetAttribute(samlDictionary.AssertionId, null);
            if (string.IsNullOrEmpty(attribute))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAssertionIdRequired")));
            }
            if (!this.IsAssertionIdValid(attribute))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAssertionIDIsInvalid", new object[] { attribute })));
            }
            this.assertionId = attribute;
            attribute        = reader3.GetAttribute(samlDictionary.Issuer, null);
            if (string.IsNullOrEmpty(attribute))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAssertionMissingIssuerAttributeOnRead")));
            }
            this.issuer = attribute;
            attribute   = reader3.GetAttribute(samlDictionary.IssueInstant, null);
            if (!string.IsNullOrEmpty(attribute))
            {
                this.issueInstant = DateTime.ParseExact(attribute, SamlConstants.AcceptedDateTimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None).ToUniversalTime();
            }
            reader3.MoveToContent();
            reader3.Read();
            if (reader3.IsStartElement(samlDictionary.Conditions, samlDictionary.Namespace))
            {
                this.conditions = samlSerializer.LoadConditions(reader3, keyInfoSerializer, outOfBandTokenResolver);
                if (this.conditions == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLUnableToLoadCondtions")));
                }
            }
            if (reader3.IsStartElement(samlDictionary.Advice, samlDictionary.Namespace))
            {
                this.advice = samlSerializer.LoadAdvice(reader3, keyInfoSerializer, outOfBandTokenResolver);
                if (this.advice == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLUnableToLoadAdvice")));
                }
            }
            while (reader3.IsStartElement())
            {
                if (reader3.IsStartElement(samlSerializer.DictionaryManager.XmlSignatureDictionary.Signature, samlSerializer.DictionaryManager.XmlSignatureDictionary.Namespace))
                {
                    break;
                }
                SamlStatement item = samlSerializer.LoadStatement(reader3, keyInfoSerializer, outOfBandTokenResolver);
                if (item == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLUnableToLoadStatement")));
                }
                this.statements.Add(item);
            }
            if (this.statements.Count == 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAssertionRequireOneStatementOnRead")));
            }
            if (reader3.IsStartElement(samlSerializer.DictionaryManager.XmlSignatureDictionary.Signature, samlSerializer.DictionaryManager.XmlSignatureDictionary.Namespace))
            {
                this.ReadSignature(reader3, keyInfoSerializer, outOfBandTokenResolver, samlSerializer);
            }
            reader3.MoveToContent();
            reader3.ReadEndElement();
            this.tokenStream = reader3.XmlTokens;
            if (this.signature != null)
            {
                this.VerifySignature(this.signature, this.verificationKey);
            }
            this.BuildCryptoList();
        }
        /// <summary>
        /// Read saml:Conditions from the given XmlReader.
        /// </summary>
        /// <param name="reader">XmlReader to read the SAML conditions from.</param>
        /// <returns>SamlConditions</returns>
        /// <exception cref="ArgumentNullException">The parameter 'reader' is null.</exception>
        /// <exception cref="XmlException">The reader is not positioned at saml:Conditions element or contains 
        /// elements that are not recognized.</exception>
        protected virtual SamlConditions ReadConditions(XmlReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            SamlConditions conditions = new SamlConditions();
            string time = reader.GetAttribute(SamlConstants.AttributeNames.NotBefore, null);
            if (!string.IsNullOrEmpty(time))
            {
                conditions.NotBefore = DateTime.ParseExact(
                    time, DateTimeFormats.Accepted, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None).ToUniversalTime();
            }

            time = reader.GetAttribute(SamlConstants.AttributeNames.NotOnOrAfter, null);
            if (!string.IsNullOrEmpty(time))
            {
                conditions.NotOnOrAfter = DateTime.ParseExact(
                    time, DateTimeFormats.Accepted, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None).ToUniversalTime();
            }

            // Saml Conditions element is an optional element and all its child element
            // are optional as well. So we can have a empty <saml:Conditions /> element
            // in a valid Saml token.
            if (reader.IsEmptyElement)
            {
                // Just issue a read to read the Empty element.
                reader.MoveToContent();
                reader.Read();
                return conditions;
            }

            reader.ReadStartElement();

            while (reader.IsStartElement())
            {
                conditions.Conditions.Add(ReadCondition(reader));
            }

            reader.ReadEndElement();

            return conditions;
        }
        /// <summary>
        /// Serialize SamlConditions to the given XmlWriter.
        /// </summary>
        /// <param name="writer">XmlWriter to which the SamlConditions is serialized.</param>
        /// <param name="conditions">SamlConditions to be serialized.</param>
        /// <exception cref="ArgumentNullException">The parameter 'writer' or 'conditions' is null.</exception>
        protected virtual void WriteConditions(XmlWriter writer, SamlConditions conditions)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (conditions == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("conditions");
            }

            writer.WriteStartElement(SamlConstants.Prefix, SamlConstants.ElementNames.Conditions, SamlConstants.Namespace);

            // SamlConditions when new'ed up will have the min and max values defined in WCF
            // which is different than our defaults. To maintin compatability with WCF behavior we will 
            // not write out SamlConditions NotBefore and NotOnOrAfter times which match the WCF
            // min and max default values as well.
            if (conditions.NotBefore != DateTimeUtil.GetMinValue(DateTimeKind.Utc) &&
                conditions.NotBefore != WCFMinValue)
            {
                writer.WriteAttributeString(
                    SamlConstants.AttributeNames.NotBefore,
                    null,
                    conditions.NotBefore.ToUniversalTime().ToString(DateTimeFormats.Generated, DateTimeFormatInfo.InvariantInfo));
            }

            if (conditions.NotOnOrAfter != DateTimeUtil.GetMaxValue(DateTimeKind.Utc) &&
                conditions.NotOnOrAfter != WCFMaxValue)
            {
                writer.WriteAttributeString(
                    SamlConstants.AttributeNames.NotOnOrAfter,
                    null,
                    conditions.NotOnOrAfter.ToUniversalTime().ToString(DateTimeFormats.Generated, DateTimeFormatInfo.InvariantInfo));
            }

            for (int i = 0; i < conditions.Conditions.Count; i++)
            {
                WriteCondition(writer, conditions.Conditions[i]);
            }

            writer.WriteEndElement();
        }
Exemple #26
0
        /// <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>
 /// Override this method to customize the parameters to create a SamlAssertion. 
 /// </summary>
 /// <param name="issuer">The Issuer of the Assertion.</param>
 /// <param name="conditions">The SamlConditions to add.</param>
 /// <param name="advice">The SamlAdvice to add.</param>
 /// <param name="statements">The SamlStatements to add.</param>
 /// <returns>A SamlAssertion.</returns>
 /// <remarks>A unique random id is created for the assertion
 /// IssueInstance is set to DateTime.UtcNow.</remarks>
 protected virtual SamlAssertion CreateAssertion(string issuer, SamlConditions conditions, SamlAdvice advice, IEnumerable<SamlStatement> statements)
 {
     return new SamlAssertion(System.IdentityModel.UniqueId.CreateRandomId(), issuer, DateTime.UtcNow, conditions, advice, statements);
 }
        public virtual void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
        {
            if (reader == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("ReadXml"));

            if (samlSerializer == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));

            XmlDictionaryReader dictionaryReader = XmlDictionaryReader.CreateDictionaryReader(reader);
            WrappedReader wrappedReader = new WrappedReader(dictionaryReader);
#pragma warning suppress 56506 // samlSerializer.DictionaryManager is never null.
            SamlDictionary dictionary = samlSerializer.DictionaryManager.SamlDictionary;

            if (!wrappedReader.IsStartElement(dictionary.Assertion, dictionary.Namespace))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLElementNotRecognized, wrappedReader.LocalName)));

            string attributeValue = wrappedReader.GetAttribute(dictionary.MajorVersion, null);
            if (string.IsNullOrEmpty(attributeValue))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAssertionMissingMajorVersionAttributeOnRead)));
            int majorVersion = Int32.Parse(attributeValue, CultureInfo.InvariantCulture);

            attributeValue = wrappedReader.GetAttribute(dictionary.MinorVersion, null);
            if (string.IsNullOrEmpty(attributeValue))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAssertionMissingMinorVersionAttributeOnRead)));

            int minorVersion = Int32.Parse(attributeValue, CultureInfo.InvariantCulture);

            if ((majorVersion != SamlConstants.MajorVersionValue) || (minorVersion != SamlConstants.MinorVersionValue))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLTokenVersionNotSupported, majorVersion, minorVersion, SamlConstants.MajorVersionValue, SamlConstants.MinorVersionValue)));
            }

            attributeValue = wrappedReader.GetAttribute(dictionary.AssertionId, null);
            if (string.IsNullOrEmpty(attributeValue))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAssertionIdRequired)));

            if (!IsAssertionIdValid(attributeValue))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAssertionIDIsInvalid, attributeValue)));

            this.assertionId = attributeValue;

            attributeValue = wrappedReader.GetAttribute(dictionary.Issuer, null);
            if (string.IsNullOrEmpty(attributeValue))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAssertionMissingIssuerAttributeOnRead)));
            this.issuer = attributeValue;

            attributeValue = wrappedReader.GetAttribute(dictionary.IssueInstant, null);
            if (!string.IsNullOrEmpty(attributeValue))
                this.issueInstant = DateTime.ParseExact(
                    attributeValue, SamlConstants.AcceptedDateTimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None).ToUniversalTime();

            wrappedReader.MoveToContent();
            wrappedReader.Read();

            if (wrappedReader.IsStartElement(dictionary.Conditions, dictionary.Namespace))
            {
                this.conditions = samlSerializer.LoadConditions(wrappedReader, keyInfoSerializer, outOfBandTokenResolver);
                if (this.conditions == null)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLUnableToLoadCondtions)));
            }

            if (wrappedReader.IsStartElement(dictionary.Advice, dictionary.Namespace))
            {
                this.advice = samlSerializer.LoadAdvice(wrappedReader, keyInfoSerializer, outOfBandTokenResolver);
                if (this.advice == null)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLUnableToLoadAdvice)));
            }

            while (wrappedReader.IsStartElement())
            {
#pragma warning suppress 56506 // samlSerializer.DictionaryManager is never null.
                if (wrappedReader.IsStartElement(samlSerializer.DictionaryManager.XmlSignatureDictionary.Signature, samlSerializer.DictionaryManager.XmlSignatureDictionary.Namespace))
                {
                    break;
                }
                else
                {
                    SamlStatement statement = samlSerializer.LoadStatement(wrappedReader, keyInfoSerializer, outOfBandTokenResolver);
                    if (statement == null)
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLUnableToLoadStatement)));
                    this.statements.Add(statement);
                }
            }

            if (this.statements.Count == 0)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAssertionRequireOneStatementOnRead)));

            if (wrappedReader.IsStartElement(samlSerializer.DictionaryManager.XmlSignatureDictionary.Signature, samlSerializer.DictionaryManager.XmlSignatureDictionary.Namespace))
                this.ReadSignature(wrappedReader, keyInfoSerializer, outOfBandTokenResolver, samlSerializer);

            wrappedReader.MoveToContent();
            wrappedReader.ReadEndElement();

            this.tokenStream = wrappedReader.XmlTokens;

            if (this.signature != null)
            {
                VerifySignature(this.signature, this.verificationKey);
            }

            BuildCryptoList();
        }
        /// <summary>
        /// Generates all the conditions for saml
        /// 
        /// 1. Lifetime condition
        /// 2. AudienceRestriction condition
        /// 
        /// </summary>
        /// <param name="tokenLifetime">Lifetime of the Token.</param>
        /// <param name="relyingPartyAddress">The endpoint address to who the token is created. The address
        /// is modelled as an AudienceRestriction condition.</param>
        /// <param name="tokenDescriptor">Contains all the other information that is used in token issuance.</param>
        /// <returns>SamlConditions</returns>
        protected virtual SamlConditions CreateConditions(Lifetime tokenLifetime, string relyingPartyAddress, SecurityTokenDescriptor tokenDescriptor)
        {
            SamlConditions conditions = new SamlConditions();
            if (tokenLifetime != null)
            {
                if (tokenLifetime.Created != null)
                {
                    conditions.NotBefore = tokenLifetime.Created.Value;
                }

                if (tokenLifetime.Expires != null)
                {
                    conditions.NotOnOrAfter = tokenLifetime.Expires.Value;
                }
            }

            if (!string.IsNullOrEmpty(relyingPartyAddress))
            {
                conditions.Conditions.Add(new SamlAudienceRestrictionCondition(new Uri[] { new Uri(relyingPartyAddress) }));
            }

            return conditions;
        }
        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);
        }
Exemple #31
0
		public void DefaultValues ()
		{
			SamlConditions c = new SamlConditions ();
			Assert.AreEqual (DateTime.MinValue.AddDays (1), c.NotBefore, "#1");
			Assert.AreEqual (DateTime.MaxValue.AddDays (-1), c.NotOnOrAfter, "#2");
		}