public override void WriteContent(XmlDictionaryWriter writer, SecurityKeyIdentifierClause clause)
            {
                SamlAssertionKeyIdentifierClause samlClause = clause as SamlAssertionKeyIdentifierClause;

                if (!string.IsNullOrEmpty(samlClause.Binding) || !string.IsNullOrEmpty(samlClause.Location) || !string.IsNullOrEmpty(samlClause.AuthorityKind))
                {
                    writer.WriteStartElement(XD.SamlDictionary.PreferredPrefix.Value, XD.SamlDictionary.AuthorityBinding, XD.SecurityJan2004Dictionary.SamlUri);
                    if (!string.IsNullOrEmpty(samlClause.Binding))
                    {
                        writer.WriteAttributeString(XD.SamlDictionary.Binding, null, samlClause.Binding);
                    }
                    if (!string.IsNullOrEmpty(samlClause.Location))
                    {
                        writer.WriteAttributeString(XD.SamlDictionary.Location, null, samlClause.Location);
                    }
                    if (!string.IsNullOrEmpty(samlClause.AuthorityKind))
                    {
                        writer.WriteAttributeString(XD.SamlDictionary.AuthorityKind, null, samlClause.AuthorityKind);
                    }
                    writer.WriteEndElement();
                }
                writer.WriteStartElement(XD.SecurityJan2004Dictionary.Prefix.Value, XD.SecurityJan2004Dictionary.KeyIdentifier, XD.SecurityJan2004Dictionary.Namespace);
                string valueType = string.IsNullOrEmpty(samlClause.ValueType) ? XD.SecurityJan2004Dictionary.SamlAssertionIdValueType.Value : samlClause.ValueType;

                writer.WriteAttributeString(XD.SecurityJan2004Dictionary.ValueType, null, valueType);
                writer.WriteString(samlClause.AssertionId);
                writer.WriteEndElement();
            }
        public override bool Matches(SecurityKeyIdentifierClause keyIdentifierClause)
        {
            SamlAssertionKeyIdentifierClause that = keyIdentifierClause as SamlAssertionKeyIdentifierClause;

            // PreSharp Bug: Parameter 'that' to this public method must be validated: A null-dereference can occur here.
            #pragma warning suppress 56506
            return(ReferenceEquals(this, that) || (that != null && that.Matches(this.assertionId)));
        }
        public override bool Matches(SecurityKeyIdentifierClause keyIdentifierClause)
        {
            SamlAssertionKeyIdentifierClause that = keyIdentifierClause as SamlAssertionKeyIdentifierClause;

            // PreSharp
            #pragma warning suppress 56506
            return(ReferenceEquals(this, that) || (that != null && that.Matches(this.assertionId)));
        }
        public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
        {
            SamlAssertionKeyIdentifierClause samlKeyIdentifierClause = keyIdentifierClause as SamlAssertionKeyIdentifierClause;

            if (samlKeyIdentifierClause != null)
            {
                return(samlKeyIdentifierClause.Matches(this.Id));
            }

            return(false);
        }
 public override bool SupportsCore(SecurityKeyIdentifierClause clause)
 {
     if (typeof(SamlAssertionKeyIdentifierClause).IsAssignableFrom(clause.GetType()))
     {
         SamlAssertionKeyIdentifierClause samlclause = clause as SamlAssertionKeyIdentifierClause;
         if ((samlclause.TokenTypeUri == null) || (samlclause.TokenTypeUri == this.GetTokenTypeUri()))
         {
             return(true);
         }
     }
     return(false);
 }
        private static void ParseValues(JsonNotifyRequestSecurityTokenResponse rstr)
        {
            rstr.ValidFrom = ulong.Parse(rstr.Created).ToDateTimeFromEpoch();
            rstr.ValidTo = ulong.Parse(rstr.Expires).ToDateTimeFromEpoch();
            rstr.SecurityTokenString = HttpUtility.HtmlDecode(rstr.SecurityTokenString);
            var xml = XElement.Parse(rstr.SecurityTokenString);

            string idAttribute = "";

            switch (rstr.TokenType)
            {
                case SecurityTokenTypes.Saml11:
                    idAttribute = "AssertionID";
                    break;
                case SecurityTokenTypes.Saml2:
                    idAttribute = "ID";
                    break;
            }

            if (rstr.TokenType == SecurityTokenTypes.Saml11 || rstr.TokenType == SecurityTokenTypes.Saml2)
            {
                var tokenId = xml.Attribute(idAttribute);
                var xmlElement = xml.ToXmlElement();
                SecurityKeyIdentifierClause clause = null;
                
                if (tokenId != null)
                {
                    clause = new SamlAssertionKeyIdentifierClause(tokenId.Value);
                }

                rstr.SecurityToken = new GenericXmlSecurityToken(
                    xmlElement,
                    null,
                    rstr.ValidFrom,
                    rstr.ValidTo,
                    clause,
                    clause,
                    new ReadOnlyCollection<IAuthorizationPolicy>(new List<IAuthorizationPolicy>()));
            }
            else if (rstr.TokenType == SecurityTokenTypes.SWT)
            {
                rstr.SecurityTokenString = Encoding.UTF8.GetString(Convert.FromBase64String(xml.Value));
            }
        }
        /// <summary>
        /// Indicates whether the <see cref="SecurityKeyIdentifierClause"/> for an assertion matches the specified <see cref="SecurityKeyIdentifierClause"/>.
        /// </summary>
        /// <param name="assertionId">Id of the assertion</param>
        /// <param name="keyIdentifierClause">A <see cref="SecurityKeyIdentifierClause"/> to match.</param>
        /// <returns>'True' if the keyIdentifier matches this. 'False' otherwise.</returns>
        public static bool Matches(string assertionId, SecurityKeyIdentifierClause keyIdentifierClause)
        {
            if (string.IsNullOrEmpty(assertionId))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("assertionId");
            }

            if (null == keyIdentifierClause)
            {
                return(false);
            }

            // Prefer our own type
            Saml2AssertionKeyIdentifierClause saml2Clause = keyIdentifierClause as Saml2AssertionKeyIdentifierClause;

            if (null != saml2Clause && StringComparer.Ordinal.Equals(assertionId, saml2Clause.Id))
            {
                return(true);
            }

            // For compatibility, match against the old WCF type.
            // WCF will read SAML2-based key identifier clauses if our
            // SecurityTokenSerializer doesn't get the chance. Unfortunately,
            // the TokenTypeUri and ValueType properties are internal, so
            // we can't check if they're for SAML2 or not. We're just going
            // to go with the fact that SAML Assertion IDs, in both versions,
            // are supposed to be sufficiently random as to not intersect.
            // So, if the AssertionID matches our Id, we'll say that's good
            // enough.
            SamlAssertionKeyIdentifierClause wcfClause = keyIdentifierClause as SamlAssertionKeyIdentifierClause;

            if (null != wcfClause && StringComparer.Ordinal.Equals(assertionId, wcfClause.AssertionId))
            {
                return(true);
            }

            // Out of options.
            return(false);
        }
		void WriteSamlAssertionKeyIdentifierClause (XmlWriter w, SamlAssertionKeyIdentifierClause ic)
		{
			w.WriteStartElement ("o", "SecurityTokenReference", Constants.WssNamespace);
			w.WriteStartElement ("o", "KeyIdentifier", Constants.WssNamespace);
			w.WriteAttributeString ("ValueType", Constants.WssKeyIdentifierSamlAssertion);
			w.WriteString (ic.AssertionId);
			w.WriteEndElement ();
			w.WriteEndElement ();
		}
        public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
        {
            SamlAssertionKeyIdentifierClause clause = keyIdentifierClause as SamlAssertionKeyIdentifierClause;

            return((clause != null) && clause.Matches(this.Id));
        }
        public override bool Matches(SecurityKeyIdentifierClause keyIdentifierClause)
        {
            SamlAssertionKeyIdentifierClause objB = keyIdentifierClause as SamlAssertionKeyIdentifierClause;

            return(object.ReferenceEquals(this, objB) || ((objB != null) && objB.Matches(this.assertionId)));
        }
        protected override SecurityToken GetTokenCore(TimeSpan timeout)
        {
            Collection<XmlElement> reqParams = new Collection<XmlElement>();
            foreach (XmlElement param in tokenRequirement.AdditionalRequestParameters)
            {
                if (param.NamespaceURI == "urn:oasis:names:tc:SAML:1.0:assertion")
                {
                    reqParams.Add(param);
                }
            }

            ISessionCache cache = (ISessionCache) Activator.CreateInstance(clientCredentials.Cache, clientCredentials.Config);

            //Check the cache for existing session.
            String id;
            List<String> idSort;
            id = clientCredentials.ClientCertificate.Certificate.Thumbprint + ";";
            id += clientCredentials.Session.Thumbprint + ";";
            idSort = new List<string>();
            foreach (XmlElement reqParam in reqParams)
            {
                String val;
                val = "{" + reqParam.GetAttribute("AttributeNamespace") + "}";
                val += reqParam.GetAttribute("AttributeName");
                val += "=";
                val += reqParam.GetElementsByTagName("AttributeValue", "urn:oasis:names:tc:SAML:1.0:assertion")[0].InnerText;
                val += ";";
                idSort.Add(val);
            }
            idSort.Sort();
            foreach (String val in idSort)
            {
                id += val;
            }
            idSort = new List<string>();
            foreach (ClaimTypeRequirement req in tokenRequirement.ClaimTypeRequirements)
            {
                String val = req.ClaimType + ";";
                idSort.Add(val);
            }
            idSort.Sort();
            foreach (String val in idSort)
            {
                id += val;
            }

            XmlNamespaceManager nsmngr = null;
            DateTime notOnOrAfter = DateTime.MinValue;

            //Get the value from the cache
            XmlElement assertion = cache.Get(id);

            //If cache had a result, check if it is still valid
            if (assertion != null)
            {
                nsmngr = new XmlNamespaceManager(assertion.OwnerDocument.NameTable);
                nsmngr.AddNamespace("saml", "urn:oasis:names:tc:SAML:1.0:assertion");

                notOnOrAfter = DateTime.Parse(assertion.SelectSingleNode("saml:Conditions/@NotOnOrAfter", nsmngr).Value, null, DateTimeStyles.RoundtripKind);

                if (notOnOrAfter < DateTime.UtcNow)
                {
                    assertion = null;
                    cache.Remove(id);
                }
            }

            //If the cache wasn't successful, create new.
            if (assertion == null)
            {
                //Get a new assertion token for the session
                StsClient target = new StsClient(tokenRequirement.IssuerBinding, tokenRequirement.IssuerAddress);
                target.Endpoint.Behaviors.Remove<ClientCredentials>();
                target.Endpoint.Behaviors.Add(new OptClientCredentials());
                target.ClientCredentials.ClientCertificate.Certificate = clientCredentials.ClientCertificate.Certificate;
                target.InnerChannel.OperationTimeout = timeout;

                assertion = target.RequestTicket("Anonymous", clientCredentials.Session, clientCredentials.Duration, reqParams, tokenRequirement.ClaimTypeRequirements);

                nsmngr = new XmlNamespaceManager(assertion.OwnerDocument.NameTable);
                nsmngr.AddNamespace("saml", "urn:oasis:names:tc:SAML:1.0:assertion");

                notOnOrAfter = DateTime.Parse(assertion.SelectSingleNode("saml:Conditions/@NotOnOrAfter", nsmngr).Value, null, DateTimeStyles.RoundtripKind);

                cache.Add(id, assertion, notOnOrAfter);
            }

            //Get some date from the assertion token
            DateTime notBefore = DateTime.Parse(assertion.SelectSingleNode("saml:Conditions/@NotBefore", nsmngr).Value, null, DateTimeStyles.RoundtripKind);
            String assertionId = assertion.SelectSingleNode("@AssertionID", nsmngr).Value;

            // Create a KeyIdentifierClause for the SamlSecurityToken
            SamlAssertionKeyIdentifierClause samlKeyIdentifierClause = new SamlAssertionKeyIdentifierClause(assertionId);

            return new GenericXmlSecurityToken(assertion, new X509SecurityToken(clientCredentials.Session), notBefore, notOnOrAfter, samlKeyIdentifierClause, samlKeyIdentifierClause, null);
        }