Beispiel #1
0
        /// <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));
        }
Beispiel #2
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");
        }
Beispiel #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");
        }
Beispiel #4
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");
        }
Beispiel #5
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());
        }
Beispiel #6
0
        /// <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));
        }
Beispiel #7
0
        private SecurityToken CreateSAMLToken(DateTime validFrom, DateTime validTo, SecurityKey signingKey, SecurityKeyIdentifier signingKeyIdentifier, SecurityKeyIdentifier proofKeyIdentifier, IList <ClaimTypeRequirement> claimReqs)
        {
            // Create list of confirmation strings
            List <string> confirmations = new List <string>();

            // Add holder-of-key string to list of confirmation strings
            confirmations.Add(SamlConstants.HolderOfKey);

            // Create SAML subject statement based on issuer member variable, confirmation string collection
            // local variable and proof key identifier parameter
            SamlSubject subject = new SamlSubject(null, null, issuer, confirmations, null, proofKeyIdentifier);

            // Create a list of SAML attributes
            List <SamlAttribute> attributes = new List <SamlAttribute>();

            // Get the claimset we want to place into the SAML assertion
            ClaimSet cs = GetClaimSet(claimReqs);

            // Iterate through the claims and add a SamlAttribute for each claim
            // Note that GetClaimSet call above returns a claimset that only contains PossessProperty claims
            foreach (Claim c in cs)
            {
                attributes.Add(new SamlAttribute(c));
            }

            // Create list of SAML statements
            List <SamlStatement> statements = new List <SamlStatement>();

            // Add a SAML attribute statement to the list of statements. Attribute statement is based on
            // subject statement and SAML attributes resulting from claims
            statements.Add(new SamlAttributeStatement(subject, attributes));

            // Create a valid from/until condition
            SamlConditions conditions = new SamlConditions(validFrom, validTo);

            // Create the SAML assertion
            SamlAssertion assertion = new SamlAssertion("_" + Guid.NewGuid().ToString(), issuer, validFrom, conditions, null, statements);

            // Set the signing credentials for the SAML assertion
            string signatureAlgorithm = GetSignatureAlgorithm(signingKey);

            assertion.SigningCredentials = new SigningCredentials(signingKey, signatureAlgorithm, SecurityAlgorithms.Sha1Digest, signingKeyIdentifier);

            SamlSecurityToken token = new SamlSecurityToken(assertion);

            Console.WriteLine("token.SecurityKeys.Count: {0}", token.SecurityKeys.Count);
            return(token);
        }
        private SecurityToken CreateSAMLToken(DateTime validFrom, DateTime validTo, SecurityKey signingKey, SecurityKeyIdentifier signingKeyIdentifier, SecurityKeyIdentifier proofKeyIdentifier)
        {
            // Create list of confirmation strings
            List <string> confirmations = new List <string>();

            // Add holder-of-key string to list of confirmation strings
            confirmations.Add("urn:oasis:names:tc:SAML:1.0:cm:holder-of-key");

            // Create SAML subject statement based on issuer member variable, confirmation string collection
            // local variable and proof key identifier parameter
            SamlSubject subject = new SamlSubject(null, null, issuer, confirmations, null, proofKeyIdentifier);

            // Create a list of SAML attributes
            List <SamlAttribute> attributes = new List <SamlAttribute>();

            // Get the claimset we want to place into the SAML assertion
            ClaimSet cs = GetClaimSet();

            // Iterate through the claims and add a SamlAttribute for each claim
            // Note that GetClaimSet call above returns a claimset that only contains PossessProperty claims
            foreach (Claim c in cs)
            {
                attributes.Add(new SamlAttribute(c));
            }

            // Create list of SAML statements
            List <SamlStatement> statements = new List <SamlStatement>();

            // Add a SAML attribute statement to the list of statements. Attribute statement is based on
            // subject statement and SAML attributes resulting from claims
            statements.Add(new SamlAttributeStatement(subject, attributes));

            // Create a valid from/until condition
            SamlConditions conditions = new SamlConditions(validFrom, validTo);

            // Add a audience Uri restriction
            conditions.Conditions.Add(new SamlAudienceRestrictionCondition(new Uri[] { new Uri("http://localhost:8010/fedservice/calc") }));

            // Create the SAML assertion
            SamlAssertion assertion = new SamlAssertion("_" + Guid.NewGuid().ToString(), issuer, validFrom, conditions, null, statements);

            // Set the signing credentials for the SAML assertion
            string signatureAlgorithm = GetSignatureAlgorithm(signingKey);

            assertion.SigningCredentials = new SigningCredentials(signingKey, signatureAlgorithm, SecurityAlgorithms.Sha1Digest, signingKeyIdentifier);

            return(new SamlSecurityToken(assertion));
        }
Beispiel #9
0
        public SoapEnvelope Build()
        {
            CheckInit();
            var samlAssertionId = GenerateId("assertion");
            var requestId       = GenerateId("request");
            var bodyId          = GenerateId("id");
            var timeStampId     = GenerateId("TS");
            var x509Id          = GenerateId("X509");
            var ssin            = GetSsin(_x509Certificate.Subject);

            if (string.IsNullOrWhiteSpace(ssin))
            {
                throw new EhealthException(Constants.ErrorCodes.NoSerialNumber);
            }

            var identitySubject = ParseSubject(_x509Certificate.Subject);
            var issuerSubject   = ParseSubject(_x509Certificate.Issuer);

            _samlAttributes.Add(new SamlAttribute(Constants.EhealthStsNames.SsinCertHolderAttributeName, Constants.EhealthStsNames.SsinAttributeNamespace, ssin));
            _samlAttributes.Add(new SamlAttribute(Constants.EhealthStsNames.SsinAttributeName, Constants.EhealthStsNames.SsinAttributeNamespace, ssin));
            _samlAttributeDesignators.Add(new SamlAttributeDesignator(Constants.EhealthStsNames.SsinCertHolderAttributeName, Constants.EhealthStsNames.SsinAttributeNamespace));
            _samlAttributeDesignators.Add(new SamlAttributeDesignator(Constants.EhealthStsNames.SsinAttributeName, Constants.EhealthStsNames.SsinAttributeNamespace));
            var issueInstant       = DateTime.Now;
            var samlNameIdentifier = new SamlNameIdentifier(
                Constants.EhealthStsNames.NameIdentifierFormat,
                issuerSubject,
                identitySubject);
            var samlSubject             = new SamlSubject(samlNameIdentifier);
            var samlConditions          = new SamlConditions(issueInstant);
            var samlAttributeStatement  = new SamlAttributeStatement(samlSubject, _samlAttributes);
            var samlAssertion           = new SamlAssertion(samlAssertionId, issueInstant, identitySubject, samlConditions, samlAttributeStatement);
            var subjectConfirmationData = new SamlSubjectConfirmationData(samlAssertion);
            var subjectConfirmation     = new SamlSubjectConfirmation(Constants.EhealthStsNames.SubjectConfirmationMethod, _x509Certificate, subjectConfirmationData);
            var samlSubjectO            = new SamlSubject(samlNameIdentifier, subjectConfirmation);
            var samlAttributeQuery      = new SamlAttributeQuery(samlSubjectO, _samlAttributeDesignators);
            var samlRequest             = new SamlRequest(requestId, samlAttributeQuery);
            var body         = new SoapBody(samlRequest, bodyId);
            var soapSecurity = new SoapSecurity(DateTime.UtcNow, timeStampId, x509Id, _x509Certificate);
            var header       = new SoapHeader(soapSecurity);
            var soapEnvelope = new SoapEnvelope(header, body);

            return(soapEnvelope);
        }
        private static void Serialize(SamlConditions conditions, XmlDocument document, XmlNode root)
        {
            if (conditions == null)
            {
                throw new ArgumentNullException(nameof(conditions));
            }

            if (document == null)
            {
                throw new ArgumentNullException(nameof(document));
            }

            if (root == null)
            {
                throw new ArgumentNullException(nameof(root));
            }

            var conditionsNode = document.CreateElement(Constants.XmlPrefixes.Saml, Constants.XmlRootNames.SamlConditions, Constants.XmlNamespaces.Saml);

            conditionsNode.SetAttribute(Constants.XmlAttributeNames.SamlNotBefore, ConvertToCurrentTime(conditions.NotBefore));
            conditionsNode.SetAttribute(Constants.XmlAttributeNames.SamlNotOnOrAfter, ConvertToCurrentTime(conditions.NotOnOrAfter));
            root.AppendChild(conditionsNode);
        }
Beispiel #11
0
        /// <summary>
        /// Creates a SAML token for the specified email address.
        /// </summary>
        public static async System.Threading.Tasks.Task <UserIdentity> CreateSAMLTokenAsync(string emailAddress)
        {
            // Normally this would be done by a server that is capable of verifying that
            // the user is a legimate holder of email address. Using a local certficate to
            // signed the SAML token is a short cut that would never be done in a real system.
            CertificateIdentifier userid = new CertificateIdentifier();

            userid.StoreType   = CertificateStoreType.X509Store;
            userid.StorePath   = "LocalMachine\\My";
            userid.SubjectName = "UA Sample Client";

            X509Certificate2 certificate = await userid.Find();

            X509SecurityToken signingToken = new X509SecurityToken(certificate);

            // Create list of confirmation strings
            List <string> confirmations = new List <string>();

            // Add holder-of-key string to list of confirmation strings
            confirmations.Add("urn:oasis:names:tc:SAML:1.0:cm:bearer");

            // Create SAML subject statement based on issuer member variable, confirmation string collection
            // local variable and proof key identifier parameter
            SamlSubject subject = new SamlSubject("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress", null, emailAddress);

            // Create a list of SAML attributes
            List <SamlAttribute> attributes = new List <SamlAttribute>();
            Claim claim = Claim.CreateNameClaim(emailAddress);

            attributes.Add(new SamlAttribute(claim));

            // Create list of SAML statements
            List <SamlStatement> statements = new List <SamlStatement>();

            // Add a SAML attribute statement to the list of statements. Attribute statement is based on
            // subject statement and SAML attributes resulting from claims
            statements.Add(new SamlAttributeStatement(subject, attributes));

            // Create a valid from/until condition
            DateTime validFrom = DateTime.UtcNow;
            DateTime validTo   = DateTime.UtcNow.AddHours(12);

            SamlConditions conditions = new SamlConditions(validFrom, validTo);

            // Create the SAML assertion
            SamlAssertion assertion = new SamlAssertion(
                "_" + Guid.NewGuid().ToString(),
                signingToken.Certificate.Subject,
                validFrom,
                conditions,
                null,
                statements);

            SecurityKey signingKey = new System.IdentityModel.Tokens.RsaSecurityKey((RSA)signingToken.Certificate.PrivateKey);

            // Set the signing credentials for the SAML assertion
            assertion.SigningCredentials = new SigningCredentials(
                signingKey,
                System.IdentityModel.Tokens.SecurityAlgorithms.RsaSha1Signature,
                System.IdentityModel.Tokens.SecurityAlgorithms.Sha1Digest,
                new SecurityKeyIdentifier(signingToken.CreateKeyIdentifierClause <X509ThumbprintKeyIdentifierClause>()));
            // TODO
            // return new UserIdentity(new SamlSecurityToken(assertion));
            throw new NotImplementedException();
        }
 /// <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) }));
 }
Beispiel #13
0
        /// <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();
        }
        /// <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);
        }
Beispiel #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 abstract void AddAudienceRestrictionCondition(SamlConditions samlConditions);
Beispiel #16
0
        /// <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);
        }