コード例 #1
0
        public static Saml2Assertion BuildAssertion()
        {
            var certificate        = AssertionFactroryMock.GetMockCertificate();
            var signingCredentials = new SigningCredentials(new X509AsymmetricSecurityKey(certificate), SecurityAlgorithms.RsaSha1Signature, SecurityAlgorithms.Sha1Digest, new SecurityKeyIdentifier(new X509RawDataKeyIdentifierClause(certificate)));
            var assertion          = new Saml2Assertion(new Saml2NameIdentifier("https://dg-mfb/idp/shibboleth", new Uri(NameIdentifierFormats.Entity)));

            assertion.Subject            = new Saml2Subject(new Saml2NameIdentifier("TestSubject", new Uri(NameIdentifierFormats.Persistent)));
            assertion.SigningCredentials = signingCredentials;
            return(assertion);
        }
コード例 #2
0
        /// <summary>
        /// Creates a Saml2Assertion from a ClaimsIdentity.
        /// </summary>
        /// <param name="identity">Claims to include in Assertion.</param>
        /// <param name="issuer">Issuer to include in assertion.</param>
        /// <param name="audience">Audience to set as audience restriction.</param>
        /// <returns>Saml2Assertion</returns>
        public static Saml2Assertion ToSaml2Assertion(
            this ClaimsIdentity identity,
            EntityId issuer,
            Uri audience)
        {
            if (identity == null)
            {
                throw new ArgumentNullException(nameof(identity));
            }

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

            var assertion = new Saml2Assertion(new Saml2NameIdentifier(issuer.Id))
            {
                Subject = new Saml2Subject(new Saml2NameIdentifier(
                                               identity.Claims.Single(c => c.Type == ClaimTypes.NameIdentifier).Value)),
            };

            assertion.Statements.Add(
                new Saml2AuthenticationStatement(
                    new Saml2AuthenticationContext(
                        new Uri("urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified")))
            {
                SessionIndex = identity.Claims.SingleOrDefault(
                    c => c.Type == AuthServicesClaimTypes.SessionIndex)?.Value
            });

            var attributeClaims = identity.Claims.Where(
                c => c.Type != ClaimTypes.NameIdentifier &&
                c.Type != AuthServicesClaimTypes.SessionIndex).GroupBy(c => c.Type);

            if (attributeClaims.Any())
            {
                assertion.Statements.Add(
                    new Saml2AttributeStatement(
                        attributeClaims.Select(
                            ac => new Saml2Attribute(ac.Key, ac.Select(c => c.Value)))));
            }

            assertion.Conditions = new Saml2Conditions()
            {
                NotOnOrAfter = DateTime.UtcNow.AddMinutes(2)
            };

            if (audience != null)
            {
                assertion.Conditions.AudienceRestrictions.Add(
                    new Saml2AudienceRestriction(audience));
            }

            return(assertion);
        }
コード例 #3
0
        /*public SecurityToken ExchangeAssertion(SealCard sc, string appliesTo)
         * {
         *  return ExchangeAssertion(appliesTo, sc.Xassertion);
         * }
         *
         * public SecurityToken ExchangeAssertion(IdCard sc, string appliesTo)
         * {
         *  return ExchangeAssertion(appliesTo, sc.Xassertion);
         * }
         *
         * public SecurityToken ExchangeAssertionViaGW( string appliesTo)
         * {
         *  return ExchangeAssertion(appliesTo, new XElement(NameSpaces.xwsse + "SecurityTokenReference", new XElement(NameSpaces.xwsse + "Reference", new XAttribute("URI", "#IDCard"))));
         * }*/

        SecurityToken ExchangeAssertion(Saml2Assertion assertion, Saml2Assertion healthAssertion, string appliesTo)
        {
            var rst = CreateWsTrustRequest();

            rst.Context   = "urn:uuid:" + Guid.NewGuid().ToString("D");
            rst.ActAs     = new SecurityTokenElement(new Saml2SecurityToken2(assertion, healthAssertion));
            rst.AppliesTo = new AppliesTo(new EndpointReference(appliesTo));
            rst.TokenType = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0";

            return(this.GetTokenCore(TimeSpan.Zero) as SealSaml2SecurityToken);
        }
コード例 #4
0
        public static Saml2Assertion MakeNemIdAssertion(X509Certificate2 certificate)
        {
            var            doc = Global.SignedTokenXml();
            Saml2Assertion sa;

            using (var rd = doc.CreateReader())
            {
                var s2sth = new Saml2SecurityTokenHandler
                {
                    /*Configuration = new SecurityTokenHandlerConfiguration
                     * {
                     *  IssuerTokenResolver = new Saml2IssuerTokenResolver()
                     * }*/
                };
                var s2st = s2sth.ReadToken(rd) as Saml2SecurityToken;
                sa = s2st.Assertion;
            }

            var ass = new Saml2Assertion(new Saml2NameIdentifier(sa.Issuer.Value))
            {
                Conditions = new Saml2Conditions
                {
                    NotOnOrAfter = DateTime.Now + TimeSpan.FromHours(8),
                    NotBefore    = DateTime.Now
                },
                Subject = new Saml2Subject(new Saml2NameIdentifier(certificate.SubjectName.Name))
            };

            ass.Subject.SubjectConfirmations.Add(new Saml2SubjectConfirmation(new Uri("urn:oasis:names:tc:SAML:2.0:cm:bearer"))
            {
                SubjectConfirmationData = new Saml2SubjectConfirmationData
                {
                    NotOnOrAfter = DateTime.Now + TimeSpan.FromHours(8),
                    Recipient    = new Uri("https://staging.fmk-online.dk/fmk/saml/SAMLAssertionConsumer")
                }
            });

            var q = from att in sa.Statements.OfType <Saml2AttributeStatement>().First().Attributes
                    select new Saml2Attribute(att.Name, att.Values.First())
            {
                NameFormat = att.NameFormat
            };

            ass.Statements.Add(new Saml2AttributeStatement(q));
            ass.Statements.Add(new Saml2AuthenticationStatement(new Saml2AuthenticationContext(new Uri("element:urn:oasis:names:tc:SAML:2.0:ac:classes:X509")), DateTime.Now));

            /*var secClause = new X509RawDataKeyIdentifierClause(certificate);
             * var issuerKeyIdentifier = new SecurityKeyIdentifier(secClause);
             * issuerKeyIdentifier.Add(secClause);*/

            ass.SigningCredentials = new X509SigningCredentials(certificate); //, SignedXml.XmlDsigRSASHA1Url, SignedXml.XmlDsigSHA1Url);
            return(ass);
        }
コード例 #5
0
        public OioSamlAssertionToIdCardRequest(XDocument doc) : base(doc)
        {
            List <XElement> assertions = GetTags(new List <ITag>()
            {
                SoapTags.Envelope, SoapTags.Body, WstTags.RequestSecurityToken, Wst14Tags.ActAs, SamlTags.Assertion
            });

            if (assertions.Count > 1)
            {
                contextToken = new Saml2AssertionSerializer().ReadSaml2Assertion(assertions[1].CreateReader());
            }
        }
コード例 #6
0
        public void CanonicalString()
        {
            var context = new CompareContext($"{this}.CanonicalString");

            var assertion        = new Saml2Assertion(new Saml2NameIdentifier("nameIdentifier"));
            var canonicalString  = assertion.CanonicalString;
            var canonicalString2 = assertion.CanonicalString;

            IdentityComparer.AreStringsEqual(canonicalString, canonicalString2, context);

            TestUtilities.AssertFailIfErrors(context);
        }
コード例 #7
0
        private Saml2Assertion CreateSaml2Assertion(Saml20Assertion assertion)
        {
            var result     = new Saml2Assertion(new Saml2NameIdentifier(assertion.Subject.Value));
            var attributes = new List <Saml2Attribute>();

            foreach (var samlAttribute in assertion.Attributes)
            {
                attributes.Add(new Saml2Attribute(samlAttribute.Name, samlAttribute.AttributeValue));
            }
            result.Statements.Add(new Saml2AttributeStatement(attributes));
            return(result);
        }
コード例 #8
0
        public override SecurityToken ReadToken(string tokenString)
        {
            var assertion = new Saml2Assertion(new Saml2NameIdentifier("__TemporaryIssuer__"));

            var wrappedSerializer = new WrappedSerializer(this, assertion);

            var sr = new StringReader(_samlXml);

            using (var reader1 = XmlReader.Create(sr))
            {
                var reader2 = new EnvelopedSignatureReader(reader1,
                                                           wrappedSerializer,
                                                           Configuration.IssuerTokenResolver,
                                                           false,
                                                           false, false);

                if (!reader2.ReadToFollowing("Signature", "http://www.w3.org/2000/09/xmldsig#") || !reader2.TryReadSignature())
                {
                    throw new FederatedAuthenticationException("Cannot find token signature",
                                                               FederatedAuthenticationErrorCode.WrongFormat);
                }

                if (!reader2.ReadToFollowing("Assertion", "urn:oasis:names:tc:SAML:2.0:assertion"))
                {
                    throw new FederatedAuthenticationException("Cannot find token assertion",
                                                               FederatedAuthenticationErrorCode.WrongFormat);
                }

                assertion = ReadAssertion(reader2);

                try
                {
                    while (reader2.Read())
                    {
                        //
                    }
                }
                catch (CryptographicException cryptographicExceptione)
                {
                    throw new FederatedAuthenticationException(cryptographicExceptione.Message,
                                                               FederatedAuthenticationErrorCode.NotTrustedIssuer,
                                                               cryptographicExceptione);
                }

                assertion.SigningCredentials = reader2.SigningCredentials;

                var           keys = ResolveSecurityKeys(assertion, Configuration.ServiceTokenResolver);
                SecurityToken token;
                TryResolveIssuerToken(assertion, Configuration.IssuerTokenResolver, out token);
                return(new Saml2SecurityToken(assertion, keys, token));
            }
        }
コード例 #9
0
        private string GetTokenString(string organizationName, bool isServiceBusScope)
        {
            // Generate Saml assertions..
            string issuerName = DefaultIssuer;
            //string issuerName = "localhost";

            Saml2NameIdentifier saml2NameIdentifier = new Saml2NameIdentifier(issuerName);             // this is the issuer name.
            Saml2Assertion      saml2Assertion      = new Saml2Assertion(saml2NameIdentifier);

            Uri acsScope = new Uri(StsPath(solutionName, isServiceBusScope));

            saml2Assertion.Conditions = new Saml2Conditions();
            saml2Assertion.Conditions
            .AudienceRestrictions.Add(new Saml2AudienceRestriction(acsScope));           // this is the ACS uri.

            saml2Assertion.Conditions.NotOnOrAfter = DateTime.Now.AddDays(1);            // Should this be utc?
            saml2Assertion.Conditions.NotBefore    = DateTime.Now.AddHours(-1);          // should this be utc?

            string certName = "localhost";

            X509Certificate2 localCert = RetrieveCertificate(certName);

            if (!localCert.HasPrivateKey)
            {
                throw new ArgumentException("Cert should have private key.", "certificate");
            }

            saml2Assertion.SigningCredentials = new X509SigningCredentials(localCert);             // this cert should have the private keys.

            // Add claim assertions.
            saml2Assertion.Statements.Add(
                new Saml2AttributeStatement(
                    new Saml2Attribute(OrganizationClaimType, organizationName)));

            // the submitter should always be a bearer.
            saml2Assertion.Subject = new Saml2Subject(new Saml2SubjectConfirmation(Saml2Constants.ConfirmationMethods.Bearer));

            // Wrap it into a security token.
            SecurityTokenHandler tokenHandler  = new Saml2SecurityTokenHandler();
            SecurityToken        securityToken = new Saml2SecurityToken(saml2Assertion);

            // Serialize the security token.
            StringBuilder sb = new StringBuilder();

            using (XmlWriter writer = XmlTextWriter.Create(new StringWriter(sb, CultureInfo.InvariantCulture)))
            {
                tokenHandler.WriteToken(writer, securityToken);
                writer.Close();
            }

            return(sb.ToString());
        }
コード例 #10
0
        public void Saml2AssertionExtensions_ToXElement_Statements()
        {
            var attributeValue = "Test";
            var assertion      = new Saml2Assertion(
                new Saml2NameIdentifier("http://idp.example.com"));

            assertion.Statements.Add(
                new Saml2AttributeStatement(new Saml2Attribute(ClaimTypes.Role, attributeValue)));

            assertion.Statements.Add(
                new Saml2AuthenticationStatement(
                    new Saml2AuthenticationContext(
                        new Uri("urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified")))
            {
                SessionIndex = "SessionIndex"
            });

            // Grab time before and after to use when comparing times. Even if
            // the time changes in the middle of the test, it should match one
            // of these times (unless you're debugging and spending more than
            // one second stepping through the code).
            var timeBefore = DateTime.UtcNow;
            var result     = assertion.ToXElement();
            var timeAfter  = DateTime.UtcNow;

            var actualAttributeXml   = result.Element(Saml2Namespaces.Saml2 + "AttributeStatement");
            var expectedAttributeXml = new XElement(Saml2Namespaces.Saml2 + "AttributeStatement",
                                                    new XElement(Saml2Namespaces.Saml2 + "Attribute",
                                                                 new XAttribute("Name", ClaimTypes.Role),
                                                                 new XElement(Saml2Namespaces.Saml2 + "AttributeValue",
                                                                              attributeValue)));

            actualAttributeXml.Should().BeEquivalentTo(expectedAttributeXml);

            var actualAuthnXml = result.Element(Saml2Namespaces.Saml2 + "AuthnStatement");

            // Compare time first and then drop it to avoid race issues
            var authnInstant = actualAuthnXml.Attribute("AuthnInstant");

            authnInstant.Value.Should().Match(
                d => d == timeBefore.ToSaml2DateTimeString() || d == timeAfter.ToSaml2DateTimeString());
            authnInstant.Remove();

            var expectedAuthnXml = new XElement(Saml2Namespaces.Saml2 + "AuthnStatement",
                                                new XAttribute("SessionIndex", "SessionIndex"),
                                                new XElement(Saml2Namespaces.Saml2 + "AuthnContext",
                                                             new XElement(Saml2Namespaces.Saml2 + "AuthnContextClassRef",
                                                                          "urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified")));

            actualAuthnXml.Should().BeEquivalentTo(expectedAuthnXml);
        }
コード例 #11
0
        public void Saml2AssertionExtensions_ToXElement_Subject()
        {
            var subjectName = "JohnDoe";
            var assertion   = new Saml2Assertion(
                new Saml2NameIdentifier("http://idp.example.com"))
            {
                Subject = new Saml2Subject(new Saml2NameIdentifier(subjectName))
            };

            var subject = assertion.ToXElement();

            subject.Element(Saml2Namespaces.Saml2 + "Subject").
            Element(Saml2Namespaces.Saml2 + "NameID").Value.Should().Be(subjectName);
        }
コード例 #12
0
        public void Saml2AssertionExtensions_ToXElement_Statements()
        {
            var attributeValue = "Test";
            var assertion      = new Saml2Assertion(
                new Saml2NameIdentifier("http://idp.example.com"));

            assertion.Statements.Add(
                new Saml2AttributeStatement(new Saml2Attribute(ClaimTypes.Role, attributeValue)));

            var subject = assertion.ToXElement();

            subject.Element(Saml2Namespaces.Saml2 + "AttributeStatement").Element(Saml2Namespaces.Saml2 + "Attribute").Attribute("Name").Value.Should().Be(ClaimTypes.Role);
            subject.Element(Saml2Namespaces.Saml2 + "AttributeStatement").Element(Saml2Namespaces.Saml2 + "Attribute").Element(Saml2Namespaces.Saml2 + "AttributeValue").Value.Should().Be(attributeValue);
        }
コード例 #13
0
        private static XmlNode GetAssertion(XmlDocument xmlDoc, SSOLoginData ssoLoginData)
        {
            if (File.Exists(certPath))
            {
                var assertion = new Saml2Assertion(new Saml2NameIdentifier("Assurex Global Test System"));

                assertion.Subject = new Saml2Subject(new Saml2NameIdentifier("*****@*****.**"));

                assertion.Subject.SubjectConfirmations.Add(new Saml2SubjectConfirmation(new Uri(SAML2_Bearer))
                { SubjectConfirmationData = new Saml2SubjectConfirmationData() { Recipient = new Uri(recepient) } });

                assertion.Statements.Add(new Saml2AuthenticationStatement(new Saml2AuthenticationContext(new Uri(SAML2_Password))));

                List<Saml2Attribute> attributes = new List<Saml2Attribute>()
                {
                    GetAttribute("UserName", ssoLoginData.Email),
                    GetAttribute("FirstName", ssoLoginData.FirstName),
                    GetAttribute("LastName", ssoLoginData.LastName),
                    GetAttribute("Country", ssoLoginData.Country),
                    GetAttribute("City", ssoLoginData.City),
                    GetAttribute("Department", ssoLoginData.Department),
                    GetAttribute("PhoneNumber", ssoLoginData.PhoneNumber),
                    GetAttribute("GroupMembership", ssoLoginData.GroupMembership),
                    GetAttribute("ErrorUrl", ssoLoginData.ErrorUrl),
                };

                assertion.Statements.Add(new Saml2AttributeStatement(attributes));

                var samlAssertion = assertion;

                var serializer = new Saml2Serializer();
                var sb = new StringBuilder();
                var settings = new XmlWriterSettings();
                using (var writer = XmlWriter.Create(sb, settings))
                {
                    serializer.WriteSaml2Assertion(writer, samlAssertion);
                }

                var samlXmlDoc = new XmlDocument();
                samlXmlDoc.LoadXml(sb.ToString());

                var xmlAssertion = xmlDoc.ImportNode(samlXmlDoc.DocumentElement, true);

                return xmlAssertion;
            }
            else
            {
                throw new Exception($"Unable to find Certificate.  Path: {certPath}");
            }
        }
コード例 #14
0
        public static Saml2Assertion MakeHealthContextAssertion(string nameIdentifier,
                                                                string subjectName,
                                                                string itSystem,
                                                                string userAuthorizationCode = null,
                                                                string userEducationCode     = null,
                                                                string userGivenName         = null,
                                                                string userSurName           = null)
        {
            var sa = new Saml2Assertion(new Saml2NameIdentifier(nameIdentifier))
            {
                Subject = new Saml2Subject(new Saml2NameIdentifier(subjectName, new Uri(SamlValues.NameidFormatX509SubjectName)))
            };

            sa.Subject.SubjectConfirmations.Add(new Saml2SubjectConfirmation(new Uri(SamlValues.ConfirmationMethodSenderVouches)));
            var attributes = new[]
            {
                userAuthorizationCode == null
                    ? null
                    : new Saml2Attribute(HealthcareSamlAttributes.UserAuthorizationCode, userAuthorizationCode)
                {
                    NameFormat = new Uri(SamlValues.NameFormatBasic)
                },
                userEducationCode == null
                    ? null
                    : new Saml2Attribute(HealthcareSamlAttributes.UserEducationCode, userEducationCode)
                {
                    NameFormat = new Uri(SamlValues.NameFormatBasic)
                },
                userGivenName == null
                    ? null
                    : new Saml2Attribute(HealthcareSamlAttributes.UserGivenName, userGivenName)
                {
                    NameFormat = new Uri(SamlValues.NameFormatBasic)
                },
                userSurName == null
                    ? null
                    : new Saml2Attribute(HealthcareSamlAttributes.UserSurName, userSurName)
                {
                    NameFormat = new Uri(SamlValues.NameFormatBasic)
                },
                new Saml2Attribute(HealthcareSamlAttributes.ItSystemName, itSystem)
                {
                    NameFormat = new Uri(SamlValues.NameFormatBasic)
                }
            };

            sa.Statements.Add(new Saml2AttributeStatement(attributes.Where(a => a != null)));
            return(sa);
        }
コード例 #15
0
        private async Task SignIn(Saml2Assertion assertion, AuthenticationProperties authenticationProperties)
        {
            System.Console.WriteLine("");
            System.Console.WriteLine("[Saml2Handler][SignIn] =>");

            var claims    = _claimFactory.Create(assertion);
            var identity  = new ClaimsIdentity(claims, Scheme.Name);
            var principal = new ClaimsPrincipal(identity);

            System.Console.WriteLine("[Saml2Handler][SignIn] => claims: " + claims);
            System.Console.WriteLine("[Saml2Handler][SignIn] => identity: " + identity);
            System.Console.WriteLine("[Saml2Handler][SignIn] => principal: " + principal);

            await Context.SignInAsync(Options.SignInScheme, principal, authenticationProperties);
        }
コード例 #16
0
        public static SecurityToken MakeBootstrapSecurityToken()
        {
            Saml2NameIdentifier identifier = new Saml2NameIdentifier("http://localhost/Echo");

            Saml2Assertion assertion = new Saml2Assertion(identifier);

            assertion.Issuer  = new Saml2NameIdentifier("idp1.test.oio.dk");
            assertion.Subject = new Saml2Subject(new Saml2NameIdentifier("Casper", new Uri("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified")));
            Saml2Attribute atribute = new Saml2Attribute("dk:gov:saml:attribute:AssuranceLevel", "2");

            atribute.NameFormat = new Uri("urn:oasis:names:tc:SAML:2.0:attrname-format:basic");

            assertion.Statements.Add(new Saml2AttributeStatement(atribute));
            return(new Saml2SecurityToken(assertion));
        }
コード例 #17
0
        public SealCard ExchangeAssertion(Saml2Assertion assertion, Saml2Assertion healthAssertion, string appliesTo)
        {
            var rst = CreateWsTrustRequest();

            rst.Context   = "urn:uuid:" + Guid.NewGuid().ToString("D");
            rst.ActAs     = new SecurityTokenElement(new Saml2SecurityToken2(assertion, healthAssertion));
            rst.AppliesTo = new AppliesTo(new EndpointReference(appliesTo));
            rst.TokenType = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0";

            //RequestSecurityTokenResponse rstr = null;
            //var token = new ChannelFactory<WSTrustChannel>().Issue(rst, out rstr) as SealSaml2SecurityToken;
            var token = GetTokenCore(TimeSpan.Zero) as SealSaml2SecurityToken;

            return(new SealCard(token.assertion));
        }
コード例 #18
0
        private static XmlDocument CreateXmlDocFromSamlAssertion(Saml2Assertion assertion)
        {
            var serializer = new Saml2Serializer();
            var sb         = new StringBuilder();
            var settings   = new XmlWriterSettings();

            using (var writer = XmlWriter.Create(sb, settings))
            {
                serializer.WriteSaml2Assertion(writer, assertion);
            }

            var doc = new XmlDocument();

            doc.LoadXml(sb.ToString());
            return(doc);
        }
コード例 #19
0
        public static ClaimsIdentity ToClaimsIdentity(this Saml2Assertion value, string authenticationType, string nameType = null, string roleType = null)
        {
            //throw new NotImplementedException();
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            var claims = value.Statements
                         .OfType <Saml2AttributeStatement>()
                         .SelectMany(a => a.Attributes, (s, atr) => atr.ToClaims(value.Issuer.Value))
                         .SelectMany(r => r)
                         .Union(ClaimsFromSubject(value.Subject, value.Issuer));

            return(new ClaimsIdentity(claims
                                      , authenticationType, nameType, roleType));
        }
コード例 #20
0
        public void Saml2AssertionExtensions_ToXElement_Conditions()
        {
            var assertion = new Saml2Assertion(
                new Saml2NameIdentifier("http://idp.example.com"))
            {
                Conditions = new Saml2Conditions()
                {
                    NotOnOrAfter = new DateTime(2099, 07, 25, 19, 52, 42, DateTimeKind.Utc)
                }
            };

            var subject = assertion.ToXElement();

            subject.Element(Saml2Namespaces.Saml2 + "Conditions")
            .Attribute("NotOnOrAfter").Value.Should().Be("2099-07-25T19:52:42Z");
        }
コード例 #21
0
        private static XElement Saml2AssertionToXElement(Saml2Assertion assertion)
        {
            var sb       = new StringBuilder();
            var settings = new XmlWriterSettings
            {
                OmitXmlDeclaration = true,
                Encoding           = Encoding.UTF8
            };

            using (var stringWriter = new StringWriter(sb))
                using (var xmlWriter = XmlWriter.Create(stringWriter, settings))
                    using (var dictionaryWriter = XmlDictionaryWriter.CreateDictionaryWriter(xmlWriter))
                    {
                        new Saml2AssertionSerializer().WriteSaml2Assertion(xmlWriter, assertion);
                    }
            return(XElement.Parse(sb.ToString()));
        }
コード例 #22
0
 public static string GetAttributeValue(this Saml2Assertion ass, string attributeName)
 {
     foreach (var contextTokenStatement in ass.Statements)
     {
         var attributeStatement = contextTokenStatement as Saml2AttributeStatement;
         if (attributeStatement != null)
         {
             foreach (var attributeStatementAttribute in attributeStatement.Attributes)
             {
                 if (attributeStatementAttribute.Name == attributeName)
                 {
                     return(attributeStatementAttribute.Values.FirstOrDefault());
                 }
             }
         }
     }
     return("");
 }
コード例 #23
0
        /// <summary>
        /// Creates a Saml2Assertion from a ClaimsIdentity.
        /// </summary>
        /// <returns>Saml2Assertion</returns>
        public static Saml2Assertion ToSaml2Assertion(this ClaimsIdentity identity, string issuer)
        {
            if (identity == null)
            {
                throw new ArgumentNullException("identity");
            }

            var assertion = new Saml2Assertion(new Saml2NameIdentifier(issuer));

            assertion.Subject = new Saml2Subject(new Saml2NameIdentifier(
                                                     identity.Claims.Single(c => c.Type == ClaimTypes.NameIdentifier).Value));

            assertion.Conditions = new Saml2Conditions()
            {
                NotOnOrAfter = DateTime.UtcNow.AddMinutes(2)
            };

            return(assertion);
        }
コード例 #24
0
        public void ShouldAddSubjectConfirmationData(string recipient)
        {
            var assertion = new Saml2Assertion(new Saml2NameIdentifier("__notused__"));

            assertion.Subject = new Saml2Subject(new Saml2NameIdentifier("__notused__"));

            var recipientUrl = new Uri(recipient);
            var token        = new Saml2SecurityToken(assertion);

            token.SetRecipient(recipientUrl);

            var bearers = token.Assertion.Subject.SubjectConfirmations.Where(c => c.Method == Saml2Constants.ConfirmationMethods.Bearer);

            Assert.Single(bearers);
            var data = bearers.Single().SubjectConfirmationData;

            Assert.NotNull(data);
            Assert.Equal(recipientUrl, data.Recipient);
            Assert.Null(data.InResponseTo);
        }
コード例 #25
0
        public SecurityToken ExchangeAssertion(Saml2Assertion assertion, Saml2Assertion healthAssertion, SealCard sc, string appliesTo)
        {
            var rst = CreateWsTrustRequest();

            rst.Context   = "urn:uuid:" + Guid.NewGuid().ToString("D");
            rst.ActAs     = new SecurityTokenElement(new Saml2SecurityToken2(assertion, healthAssertion));
            rst.AppliesTo = new AppliesTo(new EndpointReference(appliesTo));
            rst.TokenType = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0";

            return(this.GetTokenCore(TimeSpan.Zero) as SealSaml2SecurityToken);

            /*
             * RequestSecurityTokenResponse rstr = null;
             * var cc = Channel.Channel as IContextChannel;
             * using (var scope = new OperationContextScope(cc))
             * {
             *  OperationContext.Current.OutgoingMessageHeaders.Add(new SealCardMessageHeader(sc));
             *  return Channel.Issue(rst, out rstr);
             * }*/
        }
コード例 #26
0
        public IList <Claim> Create(Saml2Assertion assertion)
        {
            var claims = new List <Claim>();

            if (!string.IsNullOrEmpty(assertion.Subject.Value))
            {
                claims.Add(new Claim(Saml2ClaimTypes.Subject, assertion.Subject.Value));
                claims.Add(new Claim(Saml2ClaimTypes.Name, assertion.Subject.Value));
                claims.Add(new Claim(Saml2ClaimTypes.NameIdentifier, assertion.Subject.Value));
            }

            claims.Add(assertion.SessionIndex.IsNotNullOrEmpty()
                ? new Claim(Saml2ClaimTypes.SessionIndex, assertion.SessionIndex)
                : new Claim(Saml2ClaimTypes.SessionIndex, assertion.Id));

            claims.AddRange(assertion.Attributes.Select(attribute =>
                                                        new Claim(attribute.Name, attribute.AttributeValue[0].ToString())));

            return(claims);
        }
コード例 #27
0
        private static Saml2Assertion CreateAssertion(SigningCredentials samlpTokenSigningCredentials)
        {
            var assertion = new Saml2Assertion(new Saml2NameIdentifier("https://mojeid.regtest.nic.cz/saml/idp.xml", new Uri("urn:oasis:names:tc:SAML:2.0:nameid-format:entity")))
            {
                InclusiveNamespacesPrefixList = "ns1 ns2",
                IssueInstant       = DateTime.Parse("2019-04-08T10:30:49Z"),
                SigningCredentials = samlpTokenSigningCredentials,
                Id = new Saml2Id("id-2bMsOPOKIqeVIDLqJ")
            };

            var saml2SubjectConfirmationData = new Saml2SubjectConfirmationData
            {
                InResponseTo = new Saml2Id("ida5714d006fcc430c92aacf34ab30b166"),
                NotOnOrAfter = DateTime.Parse("2019-04-08T10:45:49Z"),
                Recipient    = new Uri("https://tnia.eidentita.cz/fpsts/processRequest.aspx")
            };
            var saml2SubjectConfirmation = new Saml2SubjectConfirmation(new Uri("urn:oasis:names:tc:SAML:2.0:cm:bearer"), saml2SubjectConfirmationData);
            var saml2Subject             = new Saml2Subject(new Saml2NameIdentifier("6dfe0399103d11411b1fa00772b6a13e0858605b80c20ea845769c57b41479ed", new Uri("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent")));

            saml2Subject.SubjectConfirmations.Add(saml2SubjectConfirmation);
            assertion.Subject = saml2Subject;

            var saml2AudienceRestrictions = new Saml2AudienceRestriction("urn:microsoft: cgg2010: fpsts");
            var saml2Conditions           = new Saml2Conditions();

            saml2Conditions.AudienceRestrictions.Add(saml2AudienceRestrictions);
            saml2Conditions.NotBefore    = DateTime.Parse("2019-04-08T10:30:49Z");
            saml2Conditions.NotOnOrAfter = DateTime.Parse("2019-04-08T10:45:49Z");
            assertion.Conditions         = saml2Conditions;

            var saml2AuthenticationContext = new Saml2AuthenticationContext(new Uri("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"));
            var saml2Statement             = new Saml2AuthenticationStatement(saml2AuthenticationContext)
            {
                AuthenticationInstant = DateTime.Parse("2019-04-08T10:30:49Z"),
                SessionIndex          = "id-oTnhrqWtcTTEntvMy"
            };

            assertion.Statements.Add(saml2Statement);

            return(assertion);
        }
コード例 #28
0
        public void Saml2AssertionExtensions_ToXElement_SubjectConfirmationData()
        {
            var subjectName  = "JohnDoe";
            var destination  = new Uri("http://sp.example.com");
            var inResponseTo = new Saml2Id("abc123");
            var notOnOrAfter = DateTime.UtcNow.AddMinutes(2);

            var assertion = new Saml2Assertion(
                new Saml2NameIdentifier("http://idp.example.com"))
            {
                Subject = new Saml2Subject(new Saml2NameIdentifier(subjectName))
                {
                    SubjectConfirmations =
                    {
                        new Saml2SubjectConfirmation(
                            new Uri("urn:oasis:names:tc:SAML:2.0:cm:bearer"),
                            new Saml2SubjectConfirmationData
                        {
                            NotOnOrAfter = notOnOrAfter,
                            InResponseTo = inResponseTo,
                            Recipient    = destination
                        })
                    }
                }
            };

            var subject = assertion.ToXElement();

            var confirmationData = subject.Element(Saml2Namespaces.Saml2 + "Subject").
                                   Element(Saml2Namespaces.Saml2 + "SubjectConfirmation").
                                   Element(Saml2Namespaces.Saml2 + "SubjectConfirmationData");

            confirmationData.
            Attribute("Recipient").Value.Should().Be(destination.OriginalString);

            confirmationData.
            Attribute("NotOnOrAfter").Value.Should().Be(notOnOrAfter.ToSaml2DateTimeString());

            confirmationData.
            Attribute("InResponseTo").Value.Should().Be(inResponseTo.Value);
        }
コード例 #29
0
        public void Saml2AssertionExtensions_ToXElement_Xml_BasicAttributes()
        {
            // Grab the current time before and after creating the assertion to
            // handle the unlikely event that the second part of the date time
            // is incremented during the test run. We don't want any heisenbugs.
            var before = DateTime.UtcNow.ToSaml2DateTimeString();

            var issuer    = "http://idp.example.com";
            var assertion = new Saml2Assertion(new Saml2NameIdentifier(issuer));

            var after = DateTime.UtcNow.ToSaml2DateTimeString();

            var subject = assertion.ToXElement();

            subject.ToString().Should().StartWith(
                @"<saml2:Assertion xmlns:saml2=""urn:oasis:names:tc:SAML:2.0:assertion");
            subject.Attribute("Version").Value.Should().Be("2.0");
            subject.Attribute("ID").Value.Should().NotBeNullOrWhiteSpace();
            subject.Attribute("IssueInstant").Value.Should().Match(
                i => i == before || i == after);
        }
コード例 #30
0
        public void ShouldAddSubjectConfirmationDataWithInResponseTo()
        {
            var inResponseTo = $"_{Guid.NewGuid()}";
            var assertion    = new Saml2Assertion(new Saml2NameIdentifier("__notused__"));

            assertion.Subject = new Saml2Subject(new Saml2NameIdentifier("__notused__"));

            var recipientUrl = new Uri("https://notused");
            var token        = new Saml2SecurityToken(assertion);

            token.SetRecipient(recipientUrl, inResponseTo);

            var bearers = token.Assertion.Subject.SubjectConfirmations.Where(c => c.Method == Saml2Constants.ConfirmationMethods.Bearer);

            Assert.Single(bearers);
            var data = bearers.Single().SubjectConfirmationData;

            Assert.NotNull(data);
            Assert.NotNull(data.InResponseTo);
            Assert.Equal(inResponseTo, data.InResponseTo.Value);
        }
コード例 #31
0
 /// <summary>
 /// Creates an instance of <see cref="Saml2SecurityKeyIdentifierClause"/>
 /// </summary>
 /// <param name="assertion">The assertion can be queried to obtain information about 
 /// the issuer when resolving the key needed to check the signature.</param>
 public Saml2SecurityKeyIdentifierClause(Saml2Assertion assertion)
     : base(typeof(Saml2SecurityKeyIdentifierClause).ToString())
 {
     this.assertion = assertion;
 }