public override void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
        {
            if (reader == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));

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

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

            if (!reader.IsStartElement(dictionary.DoNotCacheCondition, dictionary.Namespace))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLBadSchema, dictionary.DoNotCacheCondition.Value)));

            // saml:DoNotCacheCondition is a empty element. So just issue a read for
            // the empty element.
            if (reader.IsEmptyElement)
            {
                reader.MoveToContent();
                reader.Read();
                return;
            }

            reader.MoveToContent();
            reader.Read();
            reader.ReadEndElement();
        }
 public override void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
 {
     if (reader == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
     }
     if (samlSerializer == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));
     }
     SamlDictionary samlDictionary = samlSerializer.DictionaryManager.SamlDictionary;
     if (!reader.IsStartElement(samlDictionary.DoNotCacheCondition, samlDictionary.Namespace))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLBadSchema", new object[] { samlDictionary.DoNotCacheCondition.Value })));
     }
     if (reader.IsEmptyElement)
     {
         reader.MoveToContent();
         reader.Read();
     }
     else
     {
         reader.MoveToContent();
         reader.Read();
         reader.ReadEndElement();
     }
 }
		public static void Deserialize(XmlDictionaryReader reader, out IList<DirectoryControl> controls, bool mustBePresent, bool fullChecks)
		{
			string str = null;
			string str1 = null;
			bool flag;
			byte[] numArray = null;
			controls = new List<DirectoryControl>();
			if (mustBePresent || reader.IsStartElement("controls", "http://schemas.microsoft.com/2008/1/ActiveDirectory"))
			{
				reader.ReadFullStartElement("controls", "http://schemas.microsoft.com/2008/1/ActiveDirectory");
				while (reader.IsStartElement("control", "http://schemas.microsoft.com/2008/1/ActiveDirectory"))
				{
					string attribute = reader.GetAttribute("type");
					string attribute1 = reader.GetAttribute("criticality");
					reader.Read();
					if (!reader.IsStartElement("controlValue", "http://schemas.microsoft.com/2008/1/ActiveDirectory"))
					{
						numArray = null;
					}
					else
					{
						string attribute2 = reader.GetAttribute("type", "http://www.w3.org/2001/XMLSchema-instance");
						if (attribute2 != null)
						{
							XmlUtility.SplitPrefix(attribute2, out str, out str1);
							numArray = reader.ReadElementContentAsBase64();
						}
						else
						{
							throw new ArgumentException();
						}
					}
					if (!string.Equals("true", attribute1))
					{
						flag = false;
					}
					else
					{
						flag = true;
					}
					DirectoryControl directoryControl = new DirectoryControl(attribute, numArray, flag, true);
					controls.Add(directoryControl);
					reader.Read();
				}
				return;
			}
			else
			{
				return;
			}
		}
        /// <summary> 
        /// Read the policy as a LINQ expression 
        /// </summary> 
        /// <param name="rdr">XmlDictionaryReader for the policy Xml</param> 
        /// <returns></returns> 
        public Expression<Func<ClaimsPrincipal, bool>> ReadPolicy(XmlDictionaryReader rdr)
        {
            if (rdr.Name != "policy")
            {
                throw new InvalidOperationException("Invalid policy document");
            }

            rdr.Read();

            if (!rdr.IsStartElement())
            {
                rdr.ReadEndElement();
                // There are no claims inside this policy which means allow access to the page. 
                return AllowAccessForDefaultPagePolicy;
            }
            // 
            // Instantiate a parameter for the ClaimsPrincipal so it can be evaluated against 
            // each claim constraint. 
            //  
            ParameterExpression subject = Expression.Parameter(typeof(ClaimsPrincipal), "subject");
            Expression<Func<ClaimsPrincipal, bool>> result = ReadNode(rdr, subject);

            rdr.ReadEndElement();

            return result;
        }
        public void ReadXml( XmlDictionaryReader reader )
        {
            if ( reader == null )
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull( "reader" );
            }

            reader.MoveToContent();
            if ( !reader.IsStartElement( XmlEncryptionConstants.Elements.EncryptionMethod, XmlEncryptionConstants.Namespace ) )
            {
                return;
            }

            _algorithm = reader.GetAttribute( XmlEncryptionConstants.Attributes.Algorithm, null );

            if ( !reader.IsEmptyElement )
            {
                //
                // Trace unread missing element
                //

                string xml = reader.ReadOuterXml();
                if ( DiagnosticUtility.ShouldTraceWarning )
                {
                    TraceUtility.TraceString( System.Diagnostics.TraceEventType.Warning, SR.GetString( SR.ID8024, reader.Name, reader.NamespaceURI, xml ) );
                }
            }
            else
            {
                //
                // Read to the next element
                //
                reader.Read();
            }
        }
 public void ReadFrom(XmlDictionaryReader reader, long maxBufferSize)
 {
     this.ValidateReadState();
     reader.MoveToStartElement(this.OpeningElementName, NamespaceUri);
     this.encoding = reader.GetAttribute(EncodingAttribute, null);
     this.id = reader.GetAttribute(System.ServiceModel.XD.XmlEncryptionDictionary.Id, null) ?? System.ServiceModel.Security.SecurityUniqueId.Create().Value;
     this.wsuId = reader.GetAttribute(System.ServiceModel.XD.XmlEncryptionDictionary.Id, System.ServiceModel.XD.UtilityDictionary.Namespace) ?? System.ServiceModel.Security.SecurityUniqueId.Create().Value;
     this.mimeType = reader.GetAttribute(MimeTypeAttribute, null);
     this.type = reader.GetAttribute(TypeAttribute, null);
     this.ReadAdditionalAttributes(reader);
     reader.Read();
     if (reader.IsStartElement(EncryptionMethodElement.ElementName, NamespaceUri))
     {
         this.encryptionMethod.ReadFrom(reader);
     }
     if (this.tokenSerializer.CanReadKeyIdentifier(reader))
     {
         this.KeyIdentifier = this.tokenSerializer.ReadKeyIdentifier(reader);
     }
     reader.ReadStartElement(CipherDataElementName, NamespaceUri);
     reader.ReadStartElement(CipherValueElementName, NamespaceUri);
     if (maxBufferSize == 0L)
     {
         this.ReadCipherData(reader);
     }
     else
     {
         this.ReadCipherData(reader, maxBufferSize);
     }
     reader.ReadEndElement();
     reader.ReadEndElement();
     this.ReadAdditionalElements(reader);
     reader.ReadEndElement();
     this.State = EncryptionState.Read;
 }
 public BinaryBodyReader(XmlDictionaryReader reader)
 {
     reader.ReadStartElement(BinaryElementName);
     _data = reader.ReadContentAsBase64();
     if (reader.NodeType == XmlNodeType.Text) reader.Read();
     reader.ReadEndElement();
 }
Beispiel #8
0
      public static ResourceUriHeader ReadFrom(XmlDictionaryReader reader)
      {
		 reader.ReadStartElement(ElementName, ManagementNamespaces.Namespace);
         string result = reader.Value;
         reader.Read();
         reader.ReadEndElement();
         return new ResourceUriHeader(result);
      }
Beispiel #9
0
 public static IdentifierHeader ReadFrom(XmlDictionaryReader reader)
 {
    reader.ReadStartElement(ElementName, EventingActions.Namespace);
    string result = reader.Value;
    reader.Read();
    reader.ReadEndElement();
    return new IdentifierHeader(result);
 }
		/// <summary>
		/// Reads JSON as a flat dictionary into a message.
		/// </summary>
		/// <param name="messageDictionary">The message dictionary to fill with the JSON-deserialized data.</param>
		/// <param name="reader">The JSON reader.</param>
		internal static void DeserializeJsonAsFlatDictionary(IDictionary<string, string> messageDictionary, XmlDictionaryReader reader) {
			Requires.NotNull(messageDictionary, "messageDictionary");
			Requires.NotNull(reader, "reader");

			reader.Read(); // one extra one to skip the root node.
			while (reader.Read()) {
				if (reader.NodeType == XmlNodeType.EndElement) {
					// This is likely the closing </root> tag.
					continue;
				}

				string key = reader.Name;
				reader.Read();
				string value = reader.ReadContentAsString();
				messageDictionary[key] = value;
			}
		}
Beispiel #11
0
        private Expression<Func<ClaimsPrincipal, bool>> ReadClaim(XmlDictionaryReader rdr)
        {
            string claimType = rdr.GetAttribute("claimType");
            string claimValue = rdr.GetAttribute("claimValue");

            Expression<Func<ClaimsPrincipal, bool>> hasClaim = icp => HasClaim(icp, claimType, claimValue);

            rdr.Read();

            return hasClaim;
        }
Beispiel #12
0
		protected override void OnReadBodyContents(XmlDictionaryReader reader)
		{
			base.OnReadBodyContents(reader);
			XmlReader xmlReader = reader.ReadSubtree();
			using (xmlReader)
			{
				xmlReader.Read();
				ResultSerializer.Deserialize(xmlReader, ResultSerializer.ResultDialect.WSTransfer, out this._entry);
			}
			reader.Read();
			DirectoryControlSerializer.Deserialize(reader, out this._controls, false, false);
			reader.ReadEndElement();
		}
 public static FragmentTransferHeader ReadFrom(XmlDictionaryReader reader)
 {
     reader.ReadStartElement(ElementName, Const.ManagementNamespace);         
    StringBuilder fragment = new StringBuilder();
    while (reader.NodeType == XmlNodeType.Text)
    {
       fragment.Append(reader.Value);
       reader.Read();
    }
    FragmentTransferHeader result = new FragmentTransferHeader(fragment.ToString());
    reader.ReadEndElement();         
    return result;
 }
Beispiel #14
0
        private Expression<Func<ClaimsPrincipal, bool>> ReadAnd(XmlDictionaryReader rdr, ParameterExpression subject)
        {
            rdr.Read();

            BinaryExpression lambda1 = Expression.AndAlso(
                Expression.Invoke(ReadNode(rdr, subject), subject),
                Expression.Invoke(ReadNode(rdr, subject), subject));

            rdr.ReadEndElement();

            Expression<Func<ClaimsPrincipal, bool>> lambda2 = Expression.Lambda<Func<ClaimsPrincipal, bool>>(lambda1, subject);
            return lambda2;
        }
 public static MaxEnvelopeSizeHeader ReadFrom(XmlDictionaryReader reader)
 {
     reader.ReadStartElement(ElementName, Const.ManagementNamespace);
     var fragment = new StringBuilder();
     while (reader.NodeType == XmlNodeType.Text)
     {
         fragment.Append(reader.Value);
         reader.Read();
     }
     var result = new MaxEnvelopeSizeHeader(int.Parse(fragment.ToString()));
     reader.ReadEndElement();
     return result;
 }
 public static XmlDictionaryReader GetReaderAtDetailContentsFeb2005(string detailName, string detailNamespace, XmlDictionaryReader headerReader)
 {
     XmlDictionaryReader reader;
     try
     {
         WsrmFeb2005Dictionary dictionary = XD.WsrmFeb2005Dictionary;
         XmlDictionaryString namespaceUri = dictionary.Namespace;
         XmlBuffer buffer = null;
         int sectionIndex = 0;
         int depth = headerReader.Depth;
         headerReader.ReadFullStartElement(dictionary.SequenceFault, namespaceUri);
         while (headerReader.Depth > depth)
         {
             if (((headerReader.NodeType == XmlNodeType.Element) && (headerReader.NamespaceURI == detailNamespace)) && (headerReader.LocalName == detailName))
             {
                 if (buffer != null)
                 {
                     return null;
                 }
                 buffer = new XmlBuffer(0x7fffffff);
                 try
                 {
                     sectionIndex = buffer.SectionCount;
                     buffer.OpenSection(headerReader.Quotas).WriteNode(headerReader, false);
                     continue;
                 }
                 finally
                 {
                     buffer.CloseSection();
                 }
             }
             if (headerReader.Depth == depth)
             {
                 break;
             }
             headerReader.Read();
         }
         if (buffer == null)
         {
             return null;
         }
         buffer.Close();
         reader = buffer.GetReader(sectionIndex);
     }
     finally
     {
         headerReader.Close();
     }
     return reader;
 }
 public void ReadFrom(XmlDictionaryReader reader, DictionaryManager dictionaryManager)
 {
     reader.MoveToStartElement(dictionaryManager.XmlSignatureDictionary.Signature, dictionaryManager.XmlSignatureDictionary.Namespace);
     this.prefix = reader.Prefix;
     this.Id = reader.GetAttribute(dictionaryManager.UtilityDictionary.IdAttribute, null);
     reader.Read();
     this.signedInfo.ReadFrom(reader, this.signedXml.TransformFactory, dictionaryManager);
     this.signatureValueElement.ReadFrom(reader, dictionaryManager);
     if (this.signedXml.SecurityTokenSerializer.CanReadKeyIdentifier(reader))
     {
         this.keyIdentifier = this.signedXml.SecurityTokenSerializer.ReadKeyIdentifier(reader);
     }
     reader.ReadEndElement();
 }
 internal static string ReadEmptyElementAndRequiredAttribute(XmlDictionaryReader reader, XmlDictionaryString name, XmlDictionaryString namespaceUri, XmlDictionaryString attributeName, out string prefix)
 {
     reader.MoveToStartElement(name, namespaceUri);
     prefix = reader.Prefix;
     bool isEmptyElement = reader.IsEmptyElement;
     string attribute = reader.GetAttribute(attributeName, null);
     if (attribute == null)
     {
         OnRequiredAttributeMissing(attributeName.Value, null);
     }
     reader.Read();
     if (!isEmptyElement)
     {
         reader.ReadEndElement();
     }
     return attribute;
 }
 public virtual void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
 {
     if (reader == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
     }
     if (samlSerializer == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));
     }
     SamlDictionary samlDictionary = samlSerializer.DictionaryManager.SamlDictionary;
     if (reader.IsEmptyElement)
     {
         reader.MoveToContent();
         reader.Read();
     }
     else
     {
         reader.MoveToContent();
         reader.Read();
         while (reader.IsStartElement())
         {
             if (!reader.IsStartElement(samlDictionary.AssertionIdReference, samlDictionary.Namespace))
             {
                 if (!reader.IsStartElement(samlDictionary.Assertion, samlDictionary.Namespace))
                 {
                     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLBadSchema", new object[] { samlDictionary.Advice.Value })));
                 }
                 SamlAssertion item = new SamlAssertion();
                 item.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
                 this.assertions.Add(item);
             }
             else
             {
                 reader.MoveToContent();
                 this.assertionIdReferences.Add(reader.ReadString());
                 reader.MoveToContent();
                 reader.ReadEndElement();
                 continue;
             }
         }
         reader.MoveToContent();
         reader.ReadEndElement();
     }
 }
Beispiel #20
0
        /// <summary>
        /// Read the policy as a LINQ expression
        /// </summary>
        /// <param name="reader">XmlDictionaryReader for the policy Xml</param>
        /// <returns></returns>
        public Expression<Func<AuthorizationContext, bool>> ReadPolicy(XmlDictionaryReader reader)
        {
            if (reader.Name != "policy")
            {
                throw new InvalidOperationException("Invalid policy document");
            }

            reader.Read();

            // Instantiate a parameter for the IClaimsPrincipal so it can be evaluated against
            // each claim.
            ParameterExpression subject = Expression.Parameter(typeof(AuthorizationContext), "subject");

            Expression<Func<AuthorizationContext, bool>> result = ReadNode(reader, subject);
            reader.ReadEndElement();

            return result;
        }
Beispiel #21
0
 public static UserSoapHeader FromReader(XmlDictionaryReader reader)
 {
     UserSoapHeader header = new UserSoapHeader();
     
     while (!reader.EOF)
     {                
         if (reader.Name == "token")
             header.Token = reader.ReadElementContentAsString();
         else if (reader.Name == "lan")
             header.Lan = reader.ReadElementContentAsString();
         else if (reader.Name == "SOAP-ENV:Body")
             break;
         else
             reader.Read();
     }
                
     return header;
 }
 public void ReadFrom(XmlDictionaryReader reader, DictionaryManager dictionaryManager)
 {
     reader.MoveToStartElement(this.elementName, dictionaryManager.XmlSignatureDictionary.Namespace);
     this.prefix = reader.Prefix;
     bool isEmptyElement = reader.IsEmptyElement;
     this.algorithm = reader.GetAttribute(dictionaryManager.XmlSignatureDictionary.Algorithm, null);
     if (this.algorithm == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(System.IdentityModel.SR.GetString("RequiredAttributeMissing", new object[] { dictionaryManager.XmlSignatureDictionary.Algorithm, this.elementName })));
     }
     reader.Read();
     reader.MoveToContent();
     if (!isEmptyElement)
     {
         reader.MoveToContent();
         reader.ReadEndElement();
     }
 }
 public void ReadFrom(XmlDictionaryReader reader, TransformFactory transformFactory, DictionaryManager dictionaryManager)
 {
     reader.MoveToStartElement(dictionaryManager.XmlSignatureDictionary.Transforms, dictionaryManager.XmlSignatureDictionary.Namespace);
     this.prefix = reader.Prefix;
     reader.Read();
     while (reader.IsStartElement(dictionaryManager.XmlSignatureDictionary.Transform, dictionaryManager.XmlSignatureDictionary.Namespace))
     {
         string attribute = reader.GetAttribute(dictionaryManager.XmlSignatureDictionary.Algorithm, null);
         Transform transform = transformFactory.CreateTransform(attribute);
         transform.ReadFrom(reader, dictionaryManager);
         this.Add(transform);
     }
     reader.MoveToContent();
     reader.ReadEndElement();
     if (this.TransformCount == 0)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(System.IdentityModel.SR.GetString("AtLeastOneTransformRequired")));
     }
 }
 public virtual void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
 {
     if (reader == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
     }
     if (samlSerializer == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));
     }
     SamlDictionary samlDictionary = samlSerializer.DictionaryManager.SamlDictionary;
     string attribute = reader.GetAttribute(samlDictionary.NotBefore, null);
     if (!string.IsNullOrEmpty(attribute))
     {
         this.notBefore = DateTime.ParseExact(attribute, SamlConstants.AcceptedDateTimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None).ToUniversalTime();
     }
     attribute = reader.GetAttribute(samlDictionary.NotOnOrAfter, null);
     if (!string.IsNullOrEmpty(attribute))
     {
         this.notOnOrAfter = DateTime.ParseExact(attribute, SamlConstants.AcceptedDateTimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None).ToUniversalTime();
     }
     if (reader.IsEmptyElement)
     {
         reader.MoveToContent();
         reader.Read();
     }
     else
     {
         reader.MoveToContent();
         reader.Read();
         while (reader.IsStartElement())
         {
             SamlCondition item = samlSerializer.LoadCondition(reader, keyInfoSerializer, outOfBandTokenResolver);
             if (item == null)
             {
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLUnableToLoadCondtion")));
             }
             this.conditions.Add(item);
         }
         reader.MoveToContent();
         reader.ReadEndElement();
     }
 }
        /// <summary>
        /// 解析Message的头
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        public static ExceptionSoapHeader FromReader(XmlDictionaryReader reader)
        {
            ExceptionSoapHeader header = new ExceptionSoapHeader();
            while (!reader.EOF)
            {
                reader.Read();
                if (reader.Name == "type" && reader.IsStartElement())
                    header.ExceptionType = (SoapExceptionType)Enum.Parse(typeof(SoapExceptionType), reader.ReadElementContentAsString());
                else if (reader.Name == "message" && reader.IsStartElement())
                    header.Message = reader.ReadElementContentAsString();
                else if (reader.Name == "stack" && reader.IsStartElement())
                    header.Stack = reader.ReadElementContentAsString();
                else if (reader.Name == "appversion" && reader.IsStartElement())
                    header.AppVersion = reader.ReadElementContentAsString();
                else
                    continue;
                
            }

            return header;
        }
 protected static EnvelopeVersion ReadStartEnvelope(XmlDictionaryReader reader)
 {
     EnvelopeVersion version;
     if (reader.IsStartElement(XD.MessageDictionary.Envelope, XD.Message12Dictionary.Namespace))
     {
         version = EnvelopeVersion.Soap12;
     }
     else
     {
         if (!reader.IsStartElement(XD.MessageDictionary.Envelope, XD.Message11Dictionary.Namespace))
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("MessageVersionUnknown")));
         }
         version = EnvelopeVersion.Soap11;
     }
     if (reader.IsEmptyElement)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("MessageBodyMissing")));
     }
     reader.Read();
     return version;
 }
Beispiel #27
0
        public Expression<Func<ClaimsPrincipal, bool>> ReadPolicy(XmlDictionaryReader rdr)
        {
            if (rdr.Name != "policy")
            {
                throw new InvalidOperationException("Invalid policy document");
            }

            rdr.Read();

            if (!rdr.IsStartElement())
            {
                rdr.ReadEndElement();
                return AllowAccessForDefaultPagePolicy;
            }

            ParameterExpression subject = Expression.Parameter(typeof(ClaimsPrincipal), "subject");
            Expression<Func<ClaimsPrincipal, bool>> result = ReadNode(rdr, subject);

            rdr.ReadEndElement();

            return result;
        }
        public override void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
        {
            if (reader == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));

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

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

            reader.MoveToContent();
            reader.Read();
            while (reader.IsStartElement())
            {
                if (reader.IsStartElement(dictionary.Audience, dictionary.Namespace))
                {
                    reader.MoveToContent();
                    string audience = reader.ReadString();
                    if (string.IsNullOrEmpty(audience))
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAudienceRestrictionInvalidAudienceValueOnRead)));

                    this.audiences.Add(new Uri(audience));
                    reader.MoveToContent();
                    reader.ReadEndElement();
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLBadSchema, dictionary.AudienceRestrictionCondition.Value)));
                }
            }

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

            reader.MoveToContent();
            reader.ReadEndElement();
        }
 public override void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
 {
     if (reader == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
     }
     if (samlSerializer == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));
     }
     SamlDictionary samlDictionary = samlSerializer.DictionaryManager.SamlDictionary;
     reader.MoveToContent();
     reader.Read();
     while (reader.IsStartElement())
     {
         if (!reader.IsStartElement(samlDictionary.Audience, samlDictionary.Namespace))
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLBadSchema", new object[] { samlDictionary.AudienceRestrictionCondition.Value })));
         }
         reader.MoveToContent();
         string str = reader.ReadString();
         if (string.IsNullOrEmpty(str))
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAudienceRestrictionInvalidAudienceValueOnRead")));
         }
         this.audiences.Add(new Uri(str));
         reader.MoveToContent();
         reader.ReadEndElement();
     }
     if (this.audiences.Count == 0)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAudienceRestrictionShouldHaveOneAudienceOnRead")));
     }
     reader.MoveToContent();
     reader.ReadEndElement();
 }
Beispiel #30
0
        private object[] GetRequestArguments(Message requestMessage, System.Xml.XmlDictionaryReader xmlReader, OperationDescription operation, HttpContext httpContext)
        {
            var arguments = new object[operation.AllParameters.Length];

            IEnumerable <Type> serviceKnownTypes = operation
                                                   .GetServiceKnownTypesHierarchy()
                                                   .Select(x => x.Type);

            // if any ordering issues, possible to rewrite like:

            /*while (!xmlReader.EOF)
             * {
             *      var parameterInfo = operation.InParameters.FirstOrDefault(p => p.Name == xmlReader.LocalName && p.Namespace == xmlReader.NamespaceURI);
             *      if (parameterInfo == null)
             *      {
             *              xmlReader.Skip();
             *              continue;
             *      }
             *      var parameterName = parameterInfo.Name;
             *      var parameterNs = parameterInfo.Namespace;
             *      ...
             * }*/

            // Find the element for the operation's data
            if (!operation.IsMessageContractRequest)
            {
                xmlReader.ReadStartElement(operation.Name, operation.Contract.Namespace);

                foreach (var parameterInfo in operation.InParameters)
                {
                    var parameterType = parameterInfo.Parameter.ParameterType;

                    if (parameterType == typeof(HttpContext))
                    {
                        arguments[parameterInfo.Index] = httpContext;
                    }
                    else
                    {
                        var argumentValue = _serializerHelper.DeserializeInputParameter(
                            xmlReader,
                            parameterType,
                            parameterInfo.Name,
                            operation.Contract.Namespace,
                            parameterInfo.Parameter.Member,
                            serviceKnownTypes);

                        //fix https://github.com/DigDes/SoapCore/issues/379 (hack, need research)
                        if (argumentValue == null)
                        {
                            argumentValue = _serializerHelper.DeserializeInputParameter(
                                xmlReader,
                                parameterType,
                                parameterInfo.Name,
                                parameterInfo.Namespace,
                                parameterInfo.Parameter.Member,
                                serviceKnownTypes);
                        }

                        arguments[parameterInfo.Index] = argumentValue;
                    }
                }
            }
            else
            {
                // MessageContracts are constrained to having one "InParameter". We can do special logic on
                // for this
                Debug.Assert(operation.InParameters.Length == 1, "MessageContracts are constrained to having one 'InParameter'");

                var parameterInfo = operation.InParameters[0];
                var parameterType = parameterInfo.Parameter.ParameterType;

                var messageContractAttribute = parameterType.GetCustomAttribute <MessageContractAttribute>();

                Debug.Assert(messageContractAttribute != null, "operation.IsMessageContractRequest should be false if this is null");

                var @namespace = parameterInfo.Namespace ?? operation.Contract.Namespace;

                if (messageContractAttribute.IsWrapped && !parameterType.GetMembersWithAttribute <MessageHeaderAttribute>().Any())
                {
                    //https://github.com/DigDes/SoapCore/issues/385
                    if (operation.DispatchMethod.GetCustomAttribute <XmlSerializerFormatAttribute>()?.Style == OperationFormatStyle.Rpc)
                    {
                        var importer = new SoapReflectionImporter(@namespace);
                        var map      = new XmlReflectionMember
                        {
                            IsReturnValue = false,
                            MemberName    = parameterInfo.Name,
                            MemberType    = parameterType
                        };
                        var mapping    = importer.ImportMembersMapping(parameterInfo.Name, @namespace, new[] { map }, false, true);
                        var serializer = XmlSerializer.FromMappings(new[] { mapping })[0];
                        var value      = serializer.Deserialize(xmlReader);
                        if (value is object[] o && o.Length > 0)
                        {
                            arguments[parameterInfo.Index] = o[0];
                        }
                    }
                    else
                    {
                        // It's wrapped so we treat it like normal!
                        arguments[parameterInfo.Index] = _serializerHelper.DeserializeInputParameter(
                            xmlReader,
                            parameterInfo.Parameter.ParameterType,
                            parameterInfo.Name,
                            @namespace,
                            parameterInfo.Parameter.Member,
                            serviceKnownTypes);
                    }
                }
                else
                {
                    var messageHeadersMembers = parameterType.GetPropertyOrFieldMembers()
                                                .Where(x => x.GetCustomAttribute <MessageHeaderAttribute>() != null)
                                                .Select(mi => new
                    {
                        MemberInfo = mi,
                        MessageHeaderMemberAttribute = mi.GetCustomAttribute <MessageHeaderAttribute>()
                    }).ToArray();

                    var wrapperObject = Activator.CreateInstance(parameterInfo.Parameter.ParameterType);

                    for (var i = 0; i < requestMessage.Headers.Count; i++)
                    {
                        var header = requestMessage.Headers[i];
                        var member = messageHeadersMembers.FirstOrDefault(x => x.MessageHeaderMemberAttribute.Name == header.Name || x.MemberInfo.Name == header.Name);

                        if (member != null)
                        {
                            var reader = requestMessage.Headers.GetReaderAtHeader(i);

                            var value = _serializerHelper.DeserializeInputParameter(
                                reader, member.MemberInfo.GetPropertyOrFieldType(),
                                member.MessageHeaderMemberAttribute.Name ?? member.MemberInfo.Name,
                                member.MessageHeaderMemberAttribute.Namespace ?? @namespace,
                                member.MemberInfo,
                                serviceKnownTypes);

                            member.MemberInfo.SetValueToPropertyOrField(wrapperObject, value);
                        }
                    }

                    // This object isn't a wrapper element, so we will hunt for the nested message body
                    // member inside of it
                    var messageBodyMembers = parameterType.GetPropertyOrFieldMembers().Where(x => x.GetCustomAttribute <MessageBodyMemberAttribute>() != null).Select(mi => new
                    {
                        Member = mi,
                        MessageBodyMemberAttribute = mi.GetCustomAttribute <MessageBodyMemberAttribute>()
                    }).OrderBy(x => x.MessageBodyMemberAttribute.Order);

                    if (messageContractAttribute.IsWrapped)
                    {
                        xmlReader.Read();
                    }

                    foreach (var messageBodyMember in messageBodyMembers)
                    {
                        var messageBodyMemberAttribute = messageBodyMember.MessageBodyMemberAttribute;
                        var messageBodyMemberInfo      = messageBodyMember.Member;

                        var innerParameterName = messageBodyMemberAttribute.Name ?? messageBodyMemberInfo.Name;
                        var innerParameterNs   = messageBodyMemberAttribute.Namespace ?? @namespace;
                        var innerParameterType = messageBodyMemberInfo.GetPropertyOrFieldType();

                        //xmlReader.MoveToStartElement(innerParameterName, innerParameterNs);
                        var innerParameter = _serializerHelper.DeserializeInputParameter(
                            xmlReader,
                            innerParameterType,
                            innerParameterName,
                            innerParameterNs,
                            parameterInfo.Parameter.Member,
                            serviceKnownTypes);

                        messageBodyMemberInfo.SetValueToPropertyOrField(wrapperObject, innerParameter);
                    }

                    arguments[parameterInfo.Index] = wrapperObject;
                }
            }

            foreach (var parameterInfo in operation.OutParameters)
            {
                if (arguments[parameterInfo.Index] != null)
                {
                    // do not overwrite input ref parameters
                    continue;
                }

                if (parameterInfo.Parameter.ParameterType.Name == "Guid&")
                {
                    arguments[parameterInfo.Index] = Guid.Empty;
                }
                else if (parameterInfo.Parameter.ParameterType.Name == "String&" || parameterInfo.Parameter.ParameterType.GetElementType().IsArray)
                {
                    arguments[parameterInfo.Index] = null;
                }
                else
                {
                    var type = parameterInfo.Parameter.ParameterType.GetElementType();
                    arguments[parameterInfo.Index] = Activator.CreateInstance(type);
                }
            }

            return(arguments);
        }
        public static JsonValue JXMLToJsonValue(XmlDictionaryReader jsonReader)
        {
            if (jsonReader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("jsonReader");
            }

            const string RootObjectName = "RootObject";
            Stack<JsonValue> jsonStack = new Stack<JsonValue>();
            string nodeType = null;
            bool isEmptyElement = false;
            JsonValue parent = new JsonObject();
            jsonStack.Push(parent);
            string currentName = RootObjectName;

            try
            {
                MoveToRootNode(jsonReader);
                while (jsonStack.Count > 0 && jsonReader.NodeType != XmlNodeType.None)
                {
                    if (parent is JsonObject && currentName == null)
                    {
                        currentName = GetMemberName(jsonReader);
                    }

                    nodeType = jsonReader.GetAttribute(TypeAttributeName) ?? StringAttributeValue;

                    if (parent is JsonArray)
                    {
                        // For arrays, the element name has to be "item"
                        if (jsonReader.Name != ItemElementName)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SG.GetString(SR.IncorrectJsonFormat)));
                        }
                    }

                    switch (nodeType)
                    {
                        case NullAttributeValue:
                        case BooleanAttributeValue:
                        case StringAttributeValue:
                        case NumberAttributeValue:
                            JsonPrimitive jsonPrimitive = ReadPrimitive(nodeType, jsonReader);
                            InsertJsonValue(jsonStack, ref parent, ref currentName, jsonPrimitive, true);
                            break;
                        case ArrayAttributeValue:
                            JsonArray jsonArray = CreateJsonArray(jsonReader, ref isEmptyElement);
                            InsertJsonValue(jsonStack, ref parent, ref currentName, jsonArray, isEmptyElement);
                            break;
                        case ObjectAttributeValue:
                            JsonObject jsonObject = CreateObjectWithTypeHint(jsonReader, ref isEmptyElement);
                            InsertJsonValue(jsonStack, ref parent, ref currentName, jsonObject, isEmptyElement);
                            break;
                        default:
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SG.GetString(SR.IncorrectJsonFormat)));
                    }

                    while (jsonReader.NodeType == XmlNodeType.EndElement && jsonStack.Count > 0)
                    {
                        jsonReader.Read();
                        SkipWhitespace(jsonReader);
                        jsonStack.Pop();
                        if (jsonStack.Count > 0)
                        {
                            parent = jsonStack.Peek();
                        }
                    }
                }
            }
            catch (XmlException xmlException)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SG.GetString(SR.IncorrectJsonFormat), xmlException));
            }

            if (jsonStack.Count != 1)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SG.GetString(SR.IncorrectJsonFormat)));
            }

            return parent[RootObjectName];
        }
Beispiel #32
0
        public virtual void WriteNode(XmlDictionaryReader reader, bool defattr)
        {
            if (reader == null)
            {
                throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(reader)));
            }
            int d = (reader.NodeType == XmlNodeType.None ? -1 : reader.Depth);

            do
            {
                XmlNodeType nodeType = reader.NodeType;
                Type        type;
                if (nodeType == XmlNodeType.Text || nodeType == XmlNodeType.Whitespace || nodeType == XmlNodeType.SignificantWhitespace)
                {
                    // This will advance if necessary, so we don't need to call Read() explicitly
                    WriteTextNode(reader, false);
                }
                else if (reader.Depth > d && reader.IsStartArray(out type))
                {
                    WriteArrayNode(reader, type);
                }
                else
                {
                    // These will not advance, so we must call Read() explicitly
                    switch (nodeType)
                    {
                    case XmlNodeType.Element:
                        WriteElementNode(reader, defattr);
                        break;

                    case XmlNodeType.CDATA:
                        WriteCData(reader.Value);
                        break;

                    case XmlNodeType.EntityReference:
                        WriteEntityRef(reader.Name);
                        break;

                    case XmlNodeType.XmlDeclaration:
                    case XmlNodeType.ProcessingInstruction:
                        WriteProcessingInstruction(reader.Name, reader.Value);
                        break;

                    case XmlNodeType.DocumentType:
                        WriteDocType(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value);
                        break;

                    case XmlNodeType.Comment:
                        WriteComment(reader.Value);
                        break;

                    case XmlNodeType.EndElement:
                        WriteFullEndElement();
                        break;
                    }
                    if (!reader.Read())
                    {
                        break;
                    }
                }
            }while (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement));
        }