Пример #1
0
        public static SamlAssertion CreateSamlAssertionFromClaims(IEnumerable <Claim> claims)
        {
            var subject = new SamlSubject()
            {
                Name = "Windows Group Claim"
            };
            var statement = new SamlAttributeStatement()
            {
                SamlSubject = subject
            };
            var assertion = new SamlAssertion()
            {
                AssertionId = string.Format("_{0}", Guid.NewGuid().ToString()),
                Issuer      = "System"
            };

            foreach (var claim in claims)
            {
                var attribute = new SamlAttribute(claim);
                statement.Attributes.Add(attribute);
            }

            assertion.Statements.Add(statement);
            SignSamlAssertion(assertion);
            return(assertion);
        }
Пример #2
0
        public void WriteXmlValid()
        {
            SamlAssertion a       = new SamlAssertion();
            SamlSubject   subject = new SamlSubject(
                SamlConstants.UserNameNamespace,
                "urn:myqualifier",
                "myname");
            SamlAttribute          attr      = new SamlAttribute(Claim.CreateNameClaim("myname"));
            SamlAttributeStatement statement =
                new SamlAttributeStatement(subject, new SamlAttribute [] { attr });

            a.Advice = new SamlAdvice(new string [] { "urn:testadvice1" });
            DateTime notBefore  = DateTime.SpecifyKind(new DateTime(2000, 1, 1), DateTimeKind.Utc);
            DateTime notOnAfter = DateTime.SpecifyKind(new DateTime(2006, 1, 1), DateTimeKind.Utc);

            a.Conditions = new SamlConditions(notBefore, notOnAfter);
            a.Statements.Add(statement);
            a.Issuer = "my_hero";
            StringWriter sw      = new StringWriter();
            string       id      = a.AssertionId;
            DateTime     instant = a.IssueInstant;

            using (XmlDictionaryWriter dw = CreateWriter(sw)) {
                a.WriteXml(dw, new SamlSerializer(), null);
            }
            string expected = String.Format("<?xml version=\"1.0\" encoding=\"utf-16\"?><saml:Assertion MajorVersion=\"1\" MinorVersion=\"1\" AssertionID=\"{0}\" Issuer=\"my_hero\" IssueInstant=\"{1}\" xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\"><saml:Conditions NotBefore=\"{3}\" NotOnOrAfter=\"{4}\" /><saml:Advice><saml:AssertionIDReference>urn:testadvice1</saml:AssertionIDReference></saml:Advice><saml:AttributeStatement><saml:Subject><saml:NameIdentifier Format=\"urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName\" NameQualifier=\"urn:myqualifier\">myname</saml:NameIdentifier></saml:Subject><saml:Attribute AttributeName=\"name\" AttributeNamespace=\"{2}\"><saml:AttributeValue>myname</saml:AttributeValue></saml:Attribute></saml:AttributeStatement></saml:Assertion>",
                                            id,
                                            instant.ToString("yyyy-MM-ddTHH:mm:ss.fff'Z'", CultureInfo.InvariantCulture),
                                            "http://schemas.xmlsoap.org/ws/2005/05/identity/claims",
                                            notBefore.ToString("yyyy-MM-ddTHH:mm:ss.fff'Z'", CultureInfo.InvariantCulture),
                                            notOnAfter.ToString("yyyy-MM-ddTHH:mm:ss.fff'Z'", CultureInfo.InvariantCulture));

            Assert.AreEqual(expected, sw.ToString());
        }
Пример #3
0
        static void Main(string[] args)
        {
            // Here we create some SAML assertion with ID and Issuer name.
            SamlAssertion assertion = new SamlAssertion();

            assertion.AssertionId = "AssertionID";
            assertion.Issuer      = "ISSUER";
            // Create some SAML subject.
            SamlSubject samlSubject = new SamlSubject();

            samlSubject.Name = "My Subject";

            //
            // Create one SAML attribute with few values.
            SamlAttribute attr = new SamlAttribute();

            attr.Namespace = "http://daenet.eu/saml";
            attr.AttributeValues.Add("Some Value 1");
            //attr.AttributeValues.Add("Some Value 2");

            attr.Name = "My ATTR Value";

            //
            // Now create the SAML statement containing one attribute and one subject.
            SamlAttributeStatement samlAttributeStatement = new SamlAttributeStatement();

            samlAttributeStatement.Attributes.Add(attr);
            samlAttributeStatement.SamlSubject = samlSubject;

            // Append the statement to the SAML assertion.
            assertion.Statements.Add(samlAttributeStatement);
        }
Пример #4
0
        public static SamlAssertion CreateSamlAssertionFromUserNameClaims(IEnumerable <Claim> claims)
        {
            var subject = new SamlSubject()
            {
                Name = "Windows Group Claim"
            };
            var statement = new SamlAttributeStatement()
            {
                SamlSubject = subject
            };
            var assertion = new SamlAssertion()
            {
                AssertionId = string.Format("_{0}", Guid.NewGuid().ToString()),
                Issuer      = "System"
            };

            foreach (var claim in claims)
            {
                var samlClaim = new Claim(claim.ClaimType, GetResourceFromSid(claim.Resource as SecurityIdentifier), claim.Right);
                var attribute = new SamlAttribute(samlClaim);
                statement.Attributes.Add(attribute);
            }

            assertion.Statements.Add(statement);
            SignSamlAssertion(assertion);
            return(assertion);
        }
Пример #5
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));
        }
Пример #6
0
        SamlSecurityToken GetSamlToken()
        {
            SamlAssertion a = new SamlAssertion();

            SamlSubject subject = new SamlSubject(
                SamlConstants.UserNameNamespace,
                "urn:myqualifier",
                "myname");
            SamlAttribute          attr      = new SamlAttribute(Claim.CreateNameClaim("myname"));
            SamlAttributeStatement statement =
                new SamlAttributeStatement(subject, new SamlAttribute [] { attr });

            a.Statements.Add(statement);
            a.Issuer = "my_hero";

            X509Certificate2          cert = new X509Certificate2(TestResourceHelper.GetFullPathOfResource("Test/Resources/test.pfx"), "mono");
            X509AsymmetricSecurityKey key  =
                new X509AsymmetricSecurityKey(cert);

            a.SigningCredentials =
                new SigningCredentials(key,
                                       SecurityAlgorithms.HmacSha1Signature,
                                       SecurityAlgorithms.Sha256Digest);
            XmlDocument doc = new XmlDocument();
            XmlWriter   w   = doc.CreateNavigator().AppendChild();

            using (XmlDictionaryWriter dw = XmlDictionaryWriter.CreateDictionaryWriter(w)) {
                a.WriteXml(dw, new SamlSerializer(), new MySecurityTokenSerializer());
            }
            Console.Error.WriteLine(doc.OuterXml);
            return(new SamlSecurityToken(a));
        }
        private static void Serialize(SamlAttributeStatement attributeStatement, XmlDocument document, XmlNode root)
        {
            if (attributeStatement == null)
            {
                throw new ArgumentNullException(nameof(attributeStatement));
            }

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

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

            var samlAttributeStatementNode = document.CreateElement(Constants.XmlPrefixes.Saml, Constants.XmlRootNames.SamlAttributeStatement, Constants.XmlNamespaces.Saml);

            Serialize(attributeStatement.Subject, document, samlAttributeStatementNode);
            if (attributeStatement.Attributes != null)
            {
                foreach (var attribute in attributeStatement.Attributes)
                {
                    Serialize(attribute, document, samlAttributeStatementNode);
                }
            }

            root.AppendChild(samlAttributeStatementNode);
        }
Пример #8
0
        private static SamlAssertion CreateAssertion(ClaimSet claims, SecurityKey signatureKey, SecurityKeyIdentifier signatureKeyIdentifier, SecurityKeyIdentifier proofKeyIdentifier, SecurityAlgorithmSuite algoSuite)
        {
            SamlSubject samlSubject = new SamlSubject(null, null, "Self", new List <string>(1)
            {
                SamlConstants.HolderOfKey
            }, null, proofKeyIdentifier);
            IList <SamlAttribute> list = new List <SamlAttribute>();

            foreach (Claim claim in claims)
            {
                if (typeof(string) == claim.Resource.GetType())
                {
                    list.Add(new SamlAttribute(claim));
                }
            }
            SamlAttributeStatement item  = new SamlAttributeStatement(samlSubject, list);
            List <SamlStatement>   list2 = new List <SamlStatement>();

            list2.Add(item);
            SigningCredentials signingCredentials = new SigningCredentials(signatureKey, algoSuite.DefaultAsymmetricSignatureAlgorithm, algoSuite.DefaultDigestAlgorithm, signatureKeyIdentifier);
            DateTime           utcNow             = DateTime.UtcNow;

            return(new SamlAssertion("_" + Guid.NewGuid().ToString(), "Self", utcNow, new SamlConditions(utcNow, utcNow + new TimeSpan(10, 0, 0)), new SamlAdvice(), list2)
            {
                SigningCredentials = signingCredentials
            });
        }
Пример #9
0
        public void DefaultValues()
        {
            SamlAttributeStatement s =
                new SamlAttributeStatement();

            Assert.IsNull(s.SamlSubject, "#1");
            Assert.AreEqual(0, s.Attributes.Count, "#2");
        }
Пример #10
0
        /// <summary>
        /// Creates a SAML assertion based on input parameters
        /// </summary>
        /// <param name="claims">A ClaimSet containing the claims to be placed into the SAML assertion</param>
        /// <param name="signatureKey">The SecurityKey that will be used to sign the SAML assertion</param>
        /// <param name="signatureKeyIdentifier">A key identifier for the signature key</param>
        /// <param name="proofKeyIdentifier">A key identifier for the proof key</param>
        /// <param name="algoSuite">The algorithm suite to use when performing cryptographic operations</param>
        /// <returns>A SAML assertion containing the passed in claims and proof key, signed by the provided signature key</returns>
        private static SamlAssertion CreateAssertion(ClaimSet claims, SecurityKey signatureKey, SecurityKeyIdentifier signatureKeyIdentifier, SecurityKeyIdentifier proofKeyIdentifier, SecurityAlgorithmSuite algoSuite)
        {
            List <string> confirmationMethods = new List <string>(1);

            // Create a confirmationMethod for HolderOfKey
            confirmationMethods.Add(SamlConstants.HolderOfKey);

            // Create a SamlSubject with proof key and confirmation method from above
            SamlSubject samlSubject = new SamlSubject(null,
                                                      null,
                                                      "Self",
                                                      confirmationMethods,
                                                      null,
                                                      proofKeyIdentifier);

            IList <SamlAttribute> samlAttributes = new List <SamlAttribute>();

            foreach (Claim c in claims)
            {
                if (typeof(string) == c.Resource.GetType())
                {
                    samlAttributes.Add(new SamlAttribute(c));
                }
            }

            // Create a SamlAttributeStatement from the passed in SamlAttribute collection and the
            // SamlSubject from above
            SamlAttributeStatement samlAttributeStatement = new SamlAttributeStatement(samlSubject, samlAttributes);

            // Put the SamlAttributeStatement into a list of SamlStatements
            List <SamlStatement> samlSubjectStatements = new List <SamlStatement>();

            samlSubjectStatements.Add(samlAttributeStatement);

            // Create a SigningCredentials instance from the signature key
            SigningCredentials signingCredentials = new SigningCredentials(signatureKey,
                                                                           algoSuite.DefaultAsymmetricSignatureAlgorithm,
                                                                           algoSuite.DefaultDigestAlgorithm,
                                                                           signatureKeyIdentifier);

            // Create a SamlAssertion from the list of SamlStatements created above
            DateTime      issueInstant  = DateTime.UtcNow;
            SamlAssertion samlAssertion = new SamlAssertion("_" + Guid.NewGuid().ToString(),
                                                            "Self",
                                                            issueInstant,
                                                            new SamlConditions(issueInstant, issueInstant + new TimeSpan(10, 0, 0)),
                                                            new SamlAdvice(),
                                                            samlSubjectStatements
                                                            );

            // Set the SigningCredentials for the SamlAssertion
            samlAssertion.SigningCredentials = signingCredentials;

            // Return the SamlAssertion
            return(samlAssertion);
        }
Пример #11
0
        private static void InitializeSecurityContext(string tokenString)
        {
            tokenString = CryptographyHelper.DecryptFromLocalMachine(tokenString);
            SettingsSecureFileStore securitySettings = new SettingsSecureFileStore();
            ServiceConfiguration    configs          = securitySettings.GetConfigurations();

            if (configs != null)
            {
                SecurityToken token = Helper.DeSerializeSecurityToken(tokenString, configs.get_STSThumbprint(), configs.get_STSThumbprintName());
                ServiceHelperFactory.get_Instance().set_BaseUri(configs.get_ServiceBaseUrl());
                ClientConfiguration settings = securitySettings.GetClientSettingsFromConfigDll();
                if (settings == null)
                {
                    Program.logger.Error("Client configurations for security service not found");
                }
                if (settings != null)
                {
                    string clientIDFromToken         = string.Empty;
                    List <RequestClaim> customClaims = new List <RequestClaim>();
                    SamlSecurityToken   samlToken    = token as SamlSecurityToken;
                    if ((samlToken == null || samlToken.Assertion == null || samlToken.Assertion.Statements == null ? false : samlToken.Assertion.Statements.Count > 0))
                    {
                        SamlAttributeStatement statements = samlToken.Assertion.Statements[0] as SamlAttributeStatement;
                        if ((statements == null || statements.Attributes == null ? false : statements.Attributes.Count > 0))
                        {
                            SamlAttribute ClientId = statements.Attributes.FirstOrDefault <SamlAttribute>((SamlAttribute z) => StringUtility.EqualsIgnoreCase(z.Name, "clientid"));
                            if ((ClientId == null || ClientId.AttributeValues == null ? false : ClientId.AttributeValues.Count > 0))
                            {
                                clientIDFromToken = ClientId.AttributeValues[0];
                                customClaims.Add(new RequestClaim("http://schemas.imanami.com/ws/2014/06/identity/claims/clientId", true, clientIDFromToken));
                            }
                        }
                    }
                    settings.set_ActAsClientUrl(ServiceHelperFactory.get_Instance().get_BaseUri());
                    NetworkCredential       creds = CredentialCache.DefaultCredentials as NetworkCredential;
                    ClaimsPrincipalSelector claimsPrincipalSelector = (clientIDFromToken == string.Empty ? new ClaimsPrincipalSelector(creds, settings, null) : new ClaimsPrincipalSelector(creds, settings, customClaims));
                    claimsPrincipalSelector.GetClaimsPrincipal();
                    ClaimsPrincipal.ClaimsPrincipalSelector = new Func <ClaimsPrincipal>(claimsPrincipalSelector.GetClaimsPrincipal);
                    if (claimsPrincipalSelector.get_ClaimsPrincipal() != null)
                    {
                        claimsPrincipalSelector.get_ClaimsPrincipal().set_ActAsToken(token);
                    }
                    ServiceHelperFactory.get_Instance().set_StsClientConfiguration(settings);
                    ServiceHelperFactory.get_Instance().set_StsUserCredentials(creds);
                }
            }
            else
            {
                Program.logger.Error("Client configurations not found");
            }
        }
Пример #12
0
        private static SamlAssertion CreateSamlAssertion(string issuer, string domain, string subject, Dictionary <string, string> attributes)
        {
            // Here we create some SAML assertion with ID and Issuer name.
            SamlAssertion assertion = new SamlAssertion();

            assertion.AssertionId = "_" + Guid.NewGuid().ToString();
            assertion.Issuer      = issuer;

            //Not before, not after conditions
            assertion.Conditions = new SamlConditions(DateTime.UtcNow,
                                                      DateTime.UtcNow.AddMinutes(10));

            //
            // Create some SAML subject.
            SamlSubject samlSubject = new SamlSubject();

            samlSubject.Name          = subject;
            samlSubject.NameQualifier = subject;

            samlSubject.ConfirmationMethods.Add("urn:oasis:names:tc:SAML:1.0:cm:bearer");
            //
            // Now create the SAML statement containing one attribute and one subject.
            SamlAttributeStatement samlAttributeStatement = new SamlAttributeStatement();

            samlAttributeStatement.SamlSubject = samlSubject;
            //
            // Create userName SAML attributes.
            foreach (KeyValuePair <string, string> attribute in attributes)
            {
                SamlAttribute attr = new SamlAttribute();
                attr.Name      = attribute.Key;
                attr.Namespace = domain;
                attr.AttributeValues.Add(subject);
                samlAttributeStatement.Attributes.Add(attr);
            }
            // Append the statement to the SAML assertion.
            assertion.Statements.Add(samlAttributeStatement);

            IPHostEntry ipEntry =
                Dns.GetHostEntry(System.Environment.MachineName);

            SamlAuthenticationStatement samlAuthenticationStatement =
                new SamlAuthenticationStatement(samlSubject,
                                                "urn:oasis:names:tc:SAML:1.0:am:password",
                                                DateTime.UtcNow, null, ipEntry.AddressList[0].ToString(),
                                                null);

            assertion.Statements.Add(samlAuthenticationStatement);
            return(assertion);
        }
Пример #13
0
        public void CompareSamlAttributeStatements()
        {
            TestUtilities.WriteHeader($"{this}.CompareSamlAttributeStatements", true);
            var context = new CompareContext($"{this}.CompareSamlAttributeStatements");
            var samlAttributeStatement1 = new SamlAttributeStatement(new SamlSubject(),
                                                                     new List <SamlAttribute> {
                new SamlAttribute("1", "2", "3")
            });
            var samlAttributeStatement2 = new SamlAttributeStatement(new SamlSubject(),
                                                                     new List <SamlAttribute>());

            IdentityComparer.AreEqual(samlAttributeStatement1, samlAttributeStatement2, context);

            Assert.True(context.Diffs.Count(s => s == "Attributes:") == 1);
        }
Пример #14
0
        public void WriteXml1()
        {
            SamlAttribute attr    = new SamlAttribute(Claim.CreateNameClaim("myname"));
            SamlSubject   subject = new SamlSubject(
                SamlConstants.UserNameNamespace,
                "urn:myqualifier",
                "myname");
            SamlAttributeStatement s = new SamlAttributeStatement(
                subject, new SamlAttribute [] { attr });
            StringWriter sw = new StringWriter();

            using (XmlDictionaryWriter dw = CreateWriter(sw)) {
                s.WriteXml(dw, new SamlSerializer(), null);
            }
            Assert.AreEqual(String.Format("<?xml version=\"1.0\" encoding=\"utf-16\"?><saml:AttributeStatement xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\"><saml:Subject><saml:NameIdentifier Format=\"urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName\" NameQualifier=\"urn:myqualifier\">myname</saml:NameIdentifier></saml:Subject><saml:Attribute AttributeName=\"name\" AttributeNamespace=\"{0}\"><saml:AttributeValue>myname</saml:AttributeValue></saml:Attribute></saml:AttributeStatement>", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims"), sw.ToString());
        }
Пример #15
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);
        }
Пример #16
0
        public static SamlSecurityToken CreateSamlToken(string issuedBy, string subject, string attrNamespace, Dictionary <string, string> claims, string certThumbPrint)
        {
            SamlAssertion assertion = new SamlAssertion();

            assertion.AssertionId = string.Format("icfi_{0}", Guid.NewGuid().ToString());
            assertion.Issuer      = issuedBy;

            SamlSubject subj = new SamlSubject();

            subj.Name = subject;

            SamlAttributeStatement samlAttrStatement = new SamlAttributeStatement();

            foreach (string claimKey in claims.Keys)
            {
                SamlAttribute attr = new SamlAttribute();
                attr.Namespace = attrNamespace;
                attr.AttributeValues.Add(claims[claimKey]);
                samlAttrStatement.Attributes.Add(attr);
            }
            samlAttrStatement.SamlSubject = subj;

            assertion.Statements.Add(samlAttrStatement);

            X509Certificate2 cert = GetCertificate(certThumbPrint);

            X509AsymmetricSecurityKey signingKey = new X509AsymmetricSecurityKey(cert);

            assertion.SigningCredentials = new SigningCredentials(
                signingKey,
                cert.PublicKey.Key.SignatureAlgorithm,
                SecurityAlgorithms.Sha1Digest,
                new SecurityKeyIdentifier(new X509ThumbprintKeyIdentifierClause(cert)));

            SamlSecurityToken samlToken = new SamlSecurityToken(assertion);

            return(samlToken);
        }
Пример #17
0
        /// <summary>
        /// Initializes the object with a .NET security token
        /// </summary>
        private void Initialize(SecurityToken token)
        {
            if (token == null)
            {
                throw new ArgumentNullException("token");
            }

            m_token = token;

            UserNameSecurityToken usernameToken = token as UserNameSecurityToken;

            if (usernameToken != null)
            {
                m_displayName     = usernameToken.UserName;
                m_tokenType       = UserTokenType.UserName;
                m_issuedTokenType = null;
                return;
            }

            X509SecurityToken x509Token = token as X509SecurityToken;

            if (x509Token != null)
            {
                m_displayName     = x509Token.Certificate.Subject;
                m_tokenType       = UserTokenType.Certificate;
                m_issuedTokenType = null;
                return;
            }

            KerberosReceiverSecurityToken kerberosToken1 = token as KerberosReceiverSecurityToken;

            if (kerberosToken1 != null)
            {
                m_displayName     = kerberosToken1.WindowsIdentity.Name;
                m_tokenType       = UserTokenType.IssuedToken;
                m_issuedTokenType = new XmlQualifiedName("", "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1");
                return;
            }

            KerberosRequestorSecurityToken kerberosToken2 = token as KerberosRequestorSecurityToken;

            if (kerberosToken2 != null)
            {
                m_displayName     = kerberosToken2.ServicePrincipalName;
                m_tokenType       = UserTokenType.IssuedToken;
                m_issuedTokenType = new XmlQualifiedName("", "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1");
                return;
            }

            SamlSecurityToken samlToken = token as SamlSecurityToken;

            if (samlToken != null)
            {
                m_displayName = "SAML";

                // find the subject of the SAML assertion.
                foreach (SamlStatement statement in samlToken.Assertion.Statements)
                {
                    SamlAttributeStatement attribute = statement as SamlAttributeStatement;

                    if (attribute != null)
                    {
                        m_displayName = attribute.SamlSubject.Name;
                        break;
                    }
                }

                m_tokenType       = UserTokenType.IssuedToken;
                m_issuedTokenType = new XmlQualifiedName("", "urn:oasis:names:tc:SAML:1.0:assertion");
                return;
            }

            m_displayName = UserTokenType.IssuedToken.ToString();
            m_tokenType   = UserTokenType.IssuedToken;
        }