示例#1
0
            public ValueProviderResult GetValue(string key)
            {
                Type   toUse = _query.Contains("Id=") ? typeof(DetailRequest) : typeof(PaginatedSearchRequestDto);
                object value = new QueryStringConverter().ConvertStringToValue(_query, toUse);

                return(new ValueProviderResult(value, null, null));
            }
示例#2
0
        public FormsPostDispatchMessageFormatter(OperationDescription od, IDispatchMessageFormatter inner, QueryStringConverter queryStringConverter)
        {
            this.inner = inner;
            this.od    = od;
            this.queryStringConverter = queryStringConverter;
            MessageDescription request = null;

            foreach (MessageDescription message in od.Messages)
            {
                if (message.Direction == MessageDirection.Input)
                {
                    request = message;
                    break;
                }
            }
            if (request != null && request.MessageType == null)
            {
                for (int i = 0; i < request.Body.Parts.Count; ++i)
                {
                    if (request.Body.Parts[i].Type == typeof(NameValueCollection))
                    {
                        this.nvcIndex = i;
                        break;
                    }
                }
            }
        }
示例#3
0
        public TResult GetResult <T, TResult>(T command)
            where T : VimeoCommand
        {
            if (this.AccessToken == null)
            {
                throw new OAuthAuthenticateException("", "AccessToken does not set.");
            }
            OAuth2Client cl = this;
            Dictionary <String, String> d = new Dictionary <string, string>();
            var url        = "https://api.vimeo.com/" + command.GetApiEndpointUrl();
            var methodName = command.GetHttpMethodName();

            if (command != null)
            {
                d = command.Map(new Dictionary <String, String>());
                var keys = d.Where(el => String.IsNullOrEmpty(el.Value)).Select(el => el.Key).ToList();
                foreach (var key in keys)
                {
                    d.Remove(key);
                }
            }
            d["access_token"] = this.AccessToken.Value;

            if (methodName == HttpMethodName.Get)
            {
                var cv = new QueryStringConverter();
                url = String.Format("{0}?{1}", url, cv.Write(d));
            }
            var cm = new HttpRequestCommand(url);

            cm.Accept     = "application/vnd.vimeo.*+json;version=3.2";
            cm.MethodName = methodName;
            if (methodName != HttpMethodName.Get)
            {
                cm.SetBodyStream(new HttpBodyFormUrlEncodedData(d));
            }

            var res = cl.GetResponse(cm);

            if (res.StatusCode != HttpStatusCode.OK &&
                res.StatusCode != HttpStatusCode.Created &&
                res.StatusCode != HttpStatusCode.Accepted)
            {
                throw new HttpResponseException(res);
            }
            var json = res.BodyText;

            try
            {
                return(JsonConvert.DeserializeObject <TResult>(json, new JsonSerializerSettings()
                {
                    MissingMemberHandling = MissingMemberHandling.Ignore
                }));
            }
            catch (JsonReaderException)
            {
                throw new HttpResponseException(res);
            }
        }
        private static void Populate(out Dictionary <int, string> pathMapping, out Dictionary <int, KeyValuePair <string, Type> > queryMapping, out int totalNumUTVars, out UriTemplate uriTemplate,
                                     OperationDescription operationDescription, QueryStringConverter qsc)
        {
            pathMapping  = new Dictionary <int, string>();
            queryMapping = new Dictionary <int, KeyValuePair <string, Type> >();
            string utString = GetUTStringOrDefault(operationDescription);

            uriTemplate = new UriTemplate(utString);
            List <string>             neededPathVars  = new List <string>(uriTemplate.PathSegmentVariableNames);
            List <string>             neededQueryVars = new List <string>(uriTemplate.QueryValueVariableNames);
            Dictionary <string, byte> alreadyGotVars  = new Dictionary <string, byte>(StringComparer.OrdinalIgnoreCase);

            totalNumUTVars = neededPathVars.Count + neededQueryVars.Count;
            for (int i = 0; i < operationDescription.Messages[0].Body.Parts.Count; ++i)
            {
                MessagePartDescription mpd = operationDescription.Messages[0].Body.Parts[i];
                string parameterName       = XmlConvert.DecodeName(mpd.Name);
                if (alreadyGotVars.ContainsKey(parameterName))
                {
                    throw new InvalidOperationException();
                }
                List <string> neededPathCopy = new List <string>(neededPathVars);
                foreach (string pathVar in neededPathCopy)
                {
                    if (string.Compare(parameterName, pathVar, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        if (mpd.Type != typeof(string))
                        {
                            throw new InvalidOperationException();
                        }
                        pathMapping.Add(i, parameterName);
                        alreadyGotVars.Add(parameterName, 0);
                        neededPathVars.Remove(pathVar);
                    }
                }
                List <string> neededQueryCopy = new List <string>(neededQueryVars);
                foreach (string queryVar in neededQueryCopy)
                {
                    if (string.Compare(parameterName, queryVar, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        if (!qsc.CanConvert(mpd.Type))
                        {
                            throw new InvalidOperationException();
                        }
                        queryMapping.Add(i, new KeyValuePair <string, Type>(parameterName, mpd.Type));
                        alreadyGotVars.Add(parameterName, 0);
                        neededQueryVars.Remove(queryVar);
                    }
                }
            }
            if (neededPathVars.Count != 0)
            {
                throw new InvalidOperationException();
            }
            if (neededQueryVars.Count != 0)
            {
                throw new InvalidOperationException();
            }
        }
        public void QueryStringConverter_StartTimeWithTimeZone()
        {
            QueryStringConverter cv = new QueryStringConverter();

            var d = cv.Parse("?StartTime=2016-06-09+10%3A58%3A14+%2B09%3A00");

            Assert.AreEqual("2016-06-09 10:58:14 +09:00", d["StartTime"]);
        }
示例#6
0
 public JsonClientFormatter(Uri baseUri, OperationDescription operationDescription, WebMessageBodyStyle defaultBodyStyle)
 {
     this.baseUri = baseUri;
     this.operationDescription = operationDescription;
     this.defaultBodyStyle     = defaultBodyStyle;
     this.queryStringConverter = new QueryStringConverter();
     this.Initialize();
 }
示例#7
0
        /// <summary>
        /// Parses and verifies the tampering protected URI.
        /// </summary>
        /// <param name="protectedUri">The tampering protected URI.</param>
        /// <param name="securityKey">The security key to use in the decryption of the <paramref name="token"/>.</param>
        /// <param name="token">The security token to decrypt and parse for a <see cref="SecurityToken"/>.</param>
        /// <param name="iv">The initialization vector (IV) to use in the decryption of the <paramref name="token"/>.</param>
        /// <param name="salt">The salt used in the computation of the integrity verification of <paramref name="protectedUri"/>.</param>
        /// <returns>An instance of the <see cref="SecurityToken"/> object if the <paramref name="protectedUri"/> is valid.</returns>
        /// <exception cref="SecurityException">This exception is thrown when an unsucessfull parse is meet, hence values has been tampered with, <paramref name="protectedUri"/> is invalid, token has expired or one or more of the necessary parameters is missing.</exception>
        public static SecurityToken ParseTamperingProtectedUri(Uri protectedUri, byte[] securityKey, string token, string iv, string salt)
        {
            if (protectedUri == null)
            {
                throw new ArgumentNullException(nameof(protectedUri));
            }
            NameValueCollection querystring = QueryStringConverter.FromString(protectedUri.Query);

            return(ParseTamperingProtectedUri(protectedUri, securityKey, token, iv, salt, HttpUtility.UrlDecode(querystring["hash"])));
        }
示例#8
0
        protected override IDispatchMessageFormatter GetRequestDispatchFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint)
        {
            // This is the default formatter for the operation, which we may wrap with our custom formatter
            IDispatchMessageFormatter formatter = base.GetRequestDispatchFormatter(operationDescription, endpoint);

            // Messages[0] is the request message
            int partsCount = operationDescription.Messages[0].Body.Parts.Count;

            // If the message doesn't have any parts, then it can't have any body content so a form post isn't applicable
            if (partsCount == 0)
            {
                return(formatter);
            }

            //For [WebInvoke] operations with body content, we want to wrap the base formatter with our HtmlFormRequestDispatchFormatter
            WebInvokeAttribute webInvoke = operationDescription.Behaviors.Find <WebInvokeAttribute>();

            if (webInvoke != null)
            {
                if (webInvoke.BodyStyle == WebMessageBodyStyle.Wrapped)
                {
                    throw new InvalidOperationException("The FormProcessingBehavior does not support wrapped requests or responses.");
                }

                // We need to determine the parts of the message that are associated with the Uri and those that are associated
                //  with the body content of the request.  To do this, we need to get the Uri template for the operation and determine
                //  how many parameters it has
                UriTemplate uriTemplate    = null;
                int         bodyPartsCount = partsCount;

                if (!string.IsNullOrEmpty(webInvoke.UriTemplate))
                {
                    uriTemplate = new UriTemplate(webInvoke.UriTemplate);
                    // The number of message parts for the request body will be the equal to the total parts for the message minus
                    //  the total number of UriTemplate variables
                    bodyPartsCount = partsCount - (uriTemplate.PathSegmentVariableNames.Count + uriTemplate.QueryValueVariableNames.Count);
                }
                else
                {
                    uriTemplate = new UriTemplate(string.Empty);
                }

                // Since we've disallowed wrapped message bodies, we can be sure that the message will only have
                //  0 or 1 message parts that are associated with the body of the request.
                if (bodyPartsCount == 1)
                {
                    QueryStringConverter converter = this.GetQueryStringConverter(operationDescription);
                    formatter = new HtmlFormRequestDispatchFormatter(operationDescription, uriTemplate, converter, formatter);
                }
            }

            return(formatter);
        }
示例#9
0
        public WebMessageFormatter(OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
        {
            this.operation = operation;
            this.endpoint  = endpoint;
            this.converter = converter;
            this.behavior  = behavior;
            ApplyWebAttribute();
            // This is a hack for WebScriptEnablingBehavior
            var jqc = converter as JsonQueryStringConverter;

            if (jqc != null)
            {
                BodyName = jqc.CustomWrapperName;
            }
        }
 public UriTemplateDispatchFormatter(OperationDescription operationDescription, IDispatchMessageFormatter bodyFormatter, QueryStringConverter qsc, string contractName, Uri baseAddress)
 {
     this.bodyFormatter = bodyFormatter;
     this.qsc           = qsc;
     this.baseAddress   = baseAddress;
     this.operationName = operationDescription.Name;
     Populate(
         out this.pathMapping,
         out this.queryMapping,
         out this.totalNumUTVars,
         out this.uriTemplate,
         operationDescription,
         qsc,
         contractName);
 }
示例#11
0
        public JsonValueFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint, QueryStringConverter queryStringConverter, int jsonValuePosition)
        {
            this.operationDescription = operationDescription;
            this.queryStringConverter = queryStringConverter;
            this.jsonValuePosition    = jsonValuePosition;

            BindingElementCollection         bindingElements = endpoint.Binding.CreateBindingElements();
            WebMessageEncodingBindingElement webEncoding     = bindingElements.Find <WebMessageEncodingBindingElement>();

            this.charset      = CharsetFromEncoding(webEncoding);
            this.readerQuotas = new XmlDictionaryReaderQuotas();
            XmlDictionaryReaderQuotas.Max.CopyTo(this.readerQuotas);
            if (webEncoding != null)
            {
                webEncoding.ReaderQuotas.CopyTo(this.readerQuotas);
            }
        }
示例#12
0
        public void DeserializeRequest(Message message, object[] parameters)
        {
            // Classes that derive from this class will implement CanDeserializeRequestBody() to
            //  tell us if we should deserialize this request or allow the default inner formatter to deserailize it.
            if (CanDeserializeRequestBody(message))
            {
                // The UriTemplateMatch instance for the request will tell us the values of the Uri variable parts
                UriTemplateMatch match = message.Properties["UriTemplateMatchResults"] as UriTemplateMatch;

                for (int x = 0; x < this.partsCount; x++)
                {
                    // For each part of the message we check if the part is the message body or a Uri variable
                    OperationParameterKind kind = operationParameterInfo[x].Kind;
                    if (kind == OperationParameterKind.MessageBody)
                    {
                        // Since this part is the message body we'll let the derived class deserailize it.
                        //  We'll provide the message body as a stream to make it easier to work with
                        Stream stream = message.GetBodyAsStream();
                        parameters[x] = DeserializeRequestBody(stream);
                    }
                    else
                    {
                        // Since this part is a Uri variable, we'll get the value for it from the UriTemplateMAtch instance
                        string value = match.BoundVariables[operationParameterInfo[x].Name];

                        if (kind == OperationParameterKind.UriQueryVariable &&
                            operationParameterInfo[x].CanConvert &&
                            value != null)
                        {
                            // Query string Uri variables should be converted to the type of the parameter from the method signature
                            parameters[x] = QueryStringConverter.ConvertStringToValue(value, operationParameterInfo[x].Type);;
                        }
                        else
                        {
                            // Path segment Uri variables are always provided as strings
                            parameters[x] = value;
                        }
                    }
                }
            }
            else
            {
                this.innerFormatter.DeserializeRequest(message, parameters);
            }
        }
示例#13
0
        private Func <ParameterInfo, object> CreateParameterBinder(UriTemplateMatch match)
        {
            QueryStringConverter converter = new QueryStringConverter();

            return(delegate(ParameterInfo pi)
            {
                string value = match.BoundVariables[pi.Name];

                if (converter.CanConvert(pi.ParameterType) && value != null)
                {
                    return converter.ConvertStringToValue(value, pi.ParameterType);
                }
                else
                {
                    return value;
                }
            });
        }
示例#14
0
        /// <summary>
        /// Converts the specified <paramref name="uriLocation"/> to a tampering protected <see cref="Uri"/>.
        /// </summary>
        /// <param name="uriLocation">The URI to protect from tampering.</param>
        /// <param name="securityKey">The security key to use for the <see cref="SecurityToken"/> encryption.</param>
        /// <param name="settings">The settings to apply to the <see cref="SecurityToken"/>.</param>
        /// <param name="algorithmType">The hash algorithm to use for the URI checksum computation. Default is <b><see cref="HashAlgorithmType.SHA1"/></b>.</param>
        /// <param name="secureUriFormat">The naming format of the required query string parameters of the tamper protected URI. Default is <b>?token={0}&amp;iv={1}&amp;salt={2}</b>, where you can change the naming of the query string parameters.</param>
        /// <param name="querystringParameterHashName">The name of the checksum parameter to append to the tampering protected URI. Default is <b>hash</b>.</param>
        /// <returns>An URI equivalent to the <paramref name="uriLocation"/> but protected from tampering - including but not limited to - MITM attacks.</returns>
        public static Uri CreateTamperingProtectedUri(string uriLocation, byte[] securityKey, SecurityTokenSettings settings, HashAlgorithmType algorithmType, string secureUriFormat, string querystringParameterHashName)
        {
            Validator.ThrowIfNullOrEmpty(uriLocation, nameof(uriLocation));
            Validator.ThrowIfNull(securityKey, nameof(securityKey));
            Validator.ThrowIfNull(settings, nameof(settings));
            Validator.ThrowIfEqual(securityKey.Length, 0, nameof(securityKey));
            Validator.ThrowIfNullOrEmpty(secureUriFormat, nameof(secureUriFormat));

            int foundArguments;

            if (!StringUtility.ParseFormat(secureUriFormat, 3, out foundArguments))
            {
                throw new ArgumentException("You must - in this order - specify three arguments for; 'token', 'iv' and 'salt'. This value cannot be exceeded nor the opposite. 'token', 'iv' and 'salt' is the default values.");
            }
            NameValueCollection formatedQuerytring = QueryStringConverter.FromString(secureUriFormat);

            SecurityToken securityToken = SecurityToken.Create(settings);

            byte[] iv = AdvancedEncryptionStandardUtility.GenerateInitializationVector();
            byte[] encryptedSecurityToken         = SecurityUtility.CreateEncryptedSecurityToken(securityToken, securityKey, iv);
            string ivAsString                     = HttpUtility.UrlEncode(Encoding.UTF8.GetString(iv, 0, iv.Length));
            string encryptedSecurityTokenAsString = HttpUtility.UrlEncode(Convert.ToBase64String(encryptedSecurityToken));
            string salt = HttpUtility.UrlEncode(StringUtility.CreateRandomString(18));
            int    indexOfQuestionMark    = uriLocation.IndexOf('?');
            string uriLocationQuerystring = indexOfQuestionMark > 0 ? uriLocation.Substring(indexOfQuestionMark) : "";

            uriLocation = indexOfQuestionMark > 0 ? uriLocation.Substring(0, indexOfQuestionMark) : uriLocation;

            NameValueCollection querystring       = QueryStringConverter.FromString(uriLocationQuerystring);
            NameValueCollection secureQuerystring = QueryStringConverter.FromString(string.Format(CultureInfo.InvariantCulture, secureUriFormat, encryptedSecurityTokenAsString, ivAsString, salt));

            secureQuerystring.Add(querystring);
            querystring = QueryStringUtility.RemoveDublets(secureQuerystring, formatedQuerytring.AllKeys);

            string secureUri = string.Format(CultureInfo.InvariantCulture, "{0}{1}", uriLocation, QueryStringConverter.FromNameValueCollection(querystring));

            secureUri += string.Format(CultureInfo.InvariantCulture, "&{0}={1}", querystringParameterHashName, HashUtility.ComputeHash(secureUri + salt + securityToken.Token, o =>
            {
                o.AlgorithmType = algorithmType;
                o.Encoding      = Encoding.UTF8;
            }).ToHexadecimal());
            return(new Uri(secureUri));
        }
        /// <summary>
        /// Initializes a new instance of the EVDispatchFormatter class
        /// </summary>
        /// <param name="od">OperationDescription object</param>
        /// <param name="inner">DispatchMessageFormatter object</param>
        /// <param name="queryStringConverter">QueryStringConverter object</param>
        public EVDispatchFormatter(OperationDescription od, IDispatchMessageFormatter inner, QueryStringConverter queryStringConverter)
        {
            this.inner = inner;
            this.od    = od;
            this.queryStringConverter = queryStringConverter;
            MessageDescription request = od.Messages.FirstOrDefault(message => message.Direction == MessageDirection.Input);

            if (request != null && request.MessageType == null)
            {
                for (int i = 0; i < request.Body.Parts.Count; ++i)
                {
                    if (request.Body.Parts[i].Type == typeof(NameValueCollection))
                    {
                        this.nvcIndex = i;
                        break;
                    }
                }
            }
        }
示例#16
0
        /// <summary>
        /// Initiates a GET request for the given operation and return the server respose (as a task).
        /// </summary>
        /// <param name="result">The result object which contains information about which operation was performed.</param>
        /// <param name="parameters">The parameters to the server method, or <c>null</c> if no parameters.</param>
        /// <param name="queryOptions">The query options if any.</param>
        /// <returns></returns>
        private Task <HttpResponseMessage> GetAsync(string operationName, IDictionary <string, object> parameters, IList <ServiceQueryPart> queryOptions, CancellationToken cancellationToken)
        {
            int i          = 0;
            var uriBuilder = new StringBuilder();

            uriBuilder.Append(operationName);

            // Parameters
            if (parameters != null && parameters.Count > 0)
            {
                var converter = new QueryStringConverter();
                foreach (var param in parameters)
                {
                    if (param.Value != null)
                    {
                        uriBuilder.Append(i++ == 0 ? '?' : '&');
                        uriBuilder.Append(Uri.EscapeDataString(param.Key));
                        uriBuilder.Append("=");

                        var value = converter.ConvertValueToString(param.Value, param.Value.GetType());
                        uriBuilder.Append(Uri.EscapeDataString(value));
                    }
                }
            }

            // Query options
            if (queryOptions != null && queryOptions.Count > 0)
            {
                foreach (var queryPart in queryOptions)
                {
                    uriBuilder.Append(i++ == 0 ? "?$" : "&$");
                    uriBuilder.Append(queryPart.QueryOperator);
                    uriBuilder.Append("=");
                    uriBuilder.Append(Uri.EscapeDataString(queryPart.Expression));
                }
            }

            // TODO: Switch to POST if uri becomes to long, we can do so by returning nul ...l
            var uri = uriBuilder.ToString();

            return(HttpClient.GetAsync(uri, cancellationToken));
        }
 public MultiDispatchFormatter(OperationDescription operation, QueryStringConverter q, ServiceEndpoint e, bool isRequest)
 {
     this.operation = operation;
     if (isRequest)
     {
         int operationParameterCount = operation.Messages[0].Body.Parts.Count;
         if (operationParameterCount > 1)
         {
             this.parameterNames = new Dictionary <string, int>();
             for (int i = 0; i < operationParameterCount; i++)
             {
                 this.parameterNames.Add(operation.Messages[0].Body.Parts[i].Name, i);
             }
         }
     }
     ep  = e;
     qsc = q;
     this.baseAddress = ep.Address.Uri;
     Populate(out this.pathMapping, out this.queryMapping, out this.totalNumUTVars, out this.uriTemplate, operation, qsc);
 }
示例#18
0
        static void Main(string[] args)
        {
            // <Snippet0>
            // <Snippet1>
            QueryStringConverter converter = new QueryStringConverter();

            // </Snippet1>
            // <Snippet2>
            if (converter.CanConvert(typeof(Int32)))
            {
                converter.ConvertStringToValue("123", typeof(Int32));
            }
            // </Snippet2>
            // <Snippet3>
            int    value    = 321;
            string strValue = converter.ConvertValueToString(value, typeof(Int32));

            Console.WriteLine("the value = {0}, the string representation of the value = {1}", value, strValue);
            // </Snippet3>
            // </Snippet0>
        }
        private String CallApi(VimeoApiEndpointInfo apiInfo, Dictionary <String, String> parameters)
        {
            var cl         = new HttpClient();
            var methodName = apiInfo.HttpMethodName.ToEnum <HttpMethodName>().Value;
            var qs         = new QueryStringConverter();
            var url        = String.Format("https://api.vimeo.com/{0}?{1}", apiInfo.ApiPath, qs.Write(parameters));

            foreach (var key in _IDParameterValues.Keys)
            {
                url = url.Replace("{" + key + "}", _IDParameterValues[key]);
            }

            var cm = new HttpRequestCommand(url);

            cm.MethodName = methodName;
            if (cm.MethodName != HttpMethodName.Get)
            {
                cm.SetBodyStream(new HttpBodyFormUrlEncodedData(parameters));
            }
            var json = cl.GetBodyText(cm);

            return(json);
        }
示例#20
0
 public MyConverter(QueryStringConverter inner)
 {
     this.inner = inner;
 }
示例#21
0
 public CustomQueryStringConverter(QueryStringConverter originalConverter)
 {
     this.originalConverter = originalConverter;
 }
        public HtmlFormRequestDispatchFormatter(OperationDescription operation, UriTemplate uriTemplate, QueryStringConverter converter, IDispatchMessageFormatter innerFormatter) :
            base(operation, uriTemplate, converter, innerFormatter)
        {
            // This formatter will only support deserializing form post data to a type if:
            //  (1) The type can be converted via the QueryStringConverter or...
            //  (2) The type meets the following requirements:
            //      (A) The type is decorated with the DataContractAttribute
            //      (B) Every public field or property that is decorated with the DataMemberAttribute is of a type that
            //          can be converted by the QueryStringConverter

            this.canConvertBodyType = this.QueryStringConverter.CanConvert(this.BodyParameterType);

            if (!this.canConvertBodyType)
            {
                if (this.BodyParameterType.GetCustomAttributes(typeof(DataContractAttribute), false).Length == 0)
                {
                    throw new NotSupportedException(
                              string.Format("Body parameter '{0}' from operation '{1}' is of type '{2}', which is not decorated with a DataContractAttribute.  " +
                                            "Only body parameter types decorated with the DataContractAttribute are supported.",
                                            this.BodyParameterName,
                                            operation.Name,
                                            this.BodyParameterType));
                }

                // For the body type, we'll need to cache information about each of the public fields/properties
                //  that is decorated with the DataMemberAttribute; we'll store this info in the bodyMembers dictionary
                //  where the member name is the dictionary key
                bodyMembers = new Dictionary <string, BodyMemberData>();

                GetBobyMemberDataForFields(operation.Name);
                GetBodyMemberDataForProperties(operation.Name);

                requiredBodyMembers = bodyMembers.Where(p => p.Value.IsRequired == true).Select(p => p.Key).ToArray();
            }
        }
示例#23
0
        protected RequestBodyDispatchFormatter(OperationDescription operation, UriTemplate uriTemplate, QueryStringConverter converter, IDispatchMessageFormatter innerFormatter)
        {
            // The inner formatter is the default formatter that WCF normally uses.  When the request can't be deserialized
            //  by our custom formatter, we'll use the default formatter.
            this.innerFormatter = innerFormatter;

            // We'll use the query string converter for both Uri query string parameters and the values of the
            //  form post data
            this.QueryStringConverter = converter;

            // Messages[0] is the request message
            MessagePartDescriptionCollection parts = operation.Messages[0].Body.Parts;

            // This partsCount includes the Uri parts (both path segment variables and query string variables)
            //  1 body content part
            partsCount = parts.Count;

            ReadOnlyCollection <string> uriPathVariables  = uriTemplate.PathSegmentVariableNames;
            ReadOnlyCollection <string> uriQueryVariables = uriTemplate.QueryValueVariableNames;

            // For each part of the message, we need to capture it's name, type, and whether it is
            //  a Uri path segment variable, a Uri query string variable or the body content
            operationParameterInfo = new OperationParameterInfo[partsCount];
            for (int x = 0; x < partsCount; x++)
            {
                string name = parts[x].Name;
                Type   type = parts[x].Type;

                // We'll assume this part is the message body, but then check if there are
                //  uri variables that match the name
                OperationParameterKind kind = OperationParameterKind.MessageBody;
                bool canConvert             = false;
                CaseInsensitiveEqualityComparer <string> comparer = new CaseInsensitiveEqualityComparer <string>();

                if (uriPathVariables.Contains(name, comparer))
                {
                    kind = OperationParameterKind.UriPathVariable;
                }
                else if (uriQueryVariables.Contains(name, comparer))
                {
                    canConvert = converter.CanConvert(type);
                    kind       = OperationParameterKind.UriQueryVariable;
                }
                else
                {
                    // If we reached here, then this part really is the message body part.
                    //  We'll store the name and type in the class properties so that derived
                    //  types have access to this information
                    this.BodyParameterName = name;
                    this.BodyParameterType = type;
                }

                operationParameterInfo[x] = new OperationParameterInfo(kind, type, name, canConvert);
            }
        }
示例#24
0
 protected WebDispatchMessageFormatter(OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
     : base(operation, endpoint, converter, behavior)
 {
 }
示例#25
0
        /// <summary>
        /// Parses and verifies the tampering protected URI.
        /// </summary>
        /// <param name="protectedUri">The tampering protected URI.</param>
        /// <param name="securityKey">The security key to use in the decryption of the <paramref name="token"/>.</param>
        /// <param name="token">The security token to decrypt and parse for a <see cref="SecurityToken"/>.</param>
        /// <param name="iv">The initialization vector (IV) to use in the decryption of the <paramref name="token"/>.</param>
        /// <param name="salt">The salt used in the computation of the integrity verification of <paramref name="protectedUri"/>.</param>
        /// <param name="hash">The checksum to verify the integrity of <paramref name="protectedUri"/>.</param>
        /// <param name="algorithmType">The hash algorithm to use for the <paramref name="protectedUri"/> checksum computation. Default is <b><see cref="HashAlgorithmType.SHA1"/></b>.</param>
        /// <param name="querystringParameterHashName">The name of the checksum parameter to remove from the <paramref name="protectedUri"/> before integrity verification. Default is <b>hash</b>.</param>
        /// <returns>An instance of the <see cref="SecurityToken"/> object if the <paramref name="protectedUri"/> is valid.</returns>
        /// <exception cref="SecurityException">This exception is thrown when an unsucessfull parse is meet, hence values has been tampered with, <paramref name="protectedUri"/> is invalid, token has expired or one or more of the necessary parameters is missing.</exception>
        public static SecurityToken ParseTamperingProtectedUri(Uri protectedUri, byte[] securityKey, string token, string iv, string salt, string hash, HashAlgorithmType algorithmType, string querystringParameterHashName)
        {
            if (protectedUri == null)
            {
                throw new ArgumentNullException(nameof(protectedUri));
            }
            if (string.IsNullOrEmpty(hash))
            {
                throw new SecurityException("Security checksum was not specified.");
            }
            if (string.IsNullOrEmpty(salt))
            {
                throw new SecurityException("Security salt was not specified.");
            }
            if (string.IsNullOrEmpty(token))
            {
                throw new SecurityException("Security token was not specified.");
            }
            if (string.IsNullOrEmpty(iv))
            {
                throw new SecurityException("Security initialization vector was not specified.");
            }
            if (querystringParameterHashName == null)
            {
                throw new ArgumentNullException(nameof(querystringParameterHashName));
            }
            if (querystringParameterHashName.Length == 0)
            {
                throw new ArgumentException("Value cannot be empty.", nameof(querystringParameterHashName));
            }

            SecurityToken securityToken;

            try
            {
                securityToken = SecurityUtility.ParseEncryptedSecurityToken(Convert.FromBase64String(token), securityKey, Encoding.UTF8.GetBytes(iv));
                string originalUriString = string.Format(CultureInfo.InvariantCulture, protectedUri.IsDefaultPort ? "{0}{1}{2}{4}" : "{0}{1}{2}:{3}{4}",
                                                         protectedUri.Scheme,
                                                         "://",
                                                         protectedUri.Host,
                                                         protectedUri.Port,
                                                         protectedUri.PathAndQuery);
                string querystring = QueryStringConverter.FromNameValueCollection(QueryStringUtility.Remove(protectedUri.Query, querystringParameterHashName));
                Uri    originalUriWithRemovedChecksum = new Uri(originalUriString);

                string urlToCompute     = string.Format(CultureInfo.InvariantCulture, "{0}{1}", new Uri(originalUriWithRemovedChecksum, originalUriWithRemovedChecksum.AbsolutePath), querystring);
                string computedChecksum = HashUtility.ComputeHash(urlToCompute + salt + securityToken.Token, o =>
                {
                    o.AlgorithmType = algorithmType;
                    o.Encoding      = Encoding.UTF8;
                }).ToHexadecimal();
                if (!string.Equals(hash, computedChecksum))
                {
                    throw new SecurityException("Security checksum is invalid.");
                }
                if (securityToken.HasExpired)
                {
                    throw new SecurityException("Security token is expired.");
                }
            }
            catch (SecurityException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SecurityException("Invalid protected URI specified.", ex);
            }

            return(securityToken);
        }
示例#26
0
 public ParameterDataProviderFromQueryString()
 {
     this.QueryStringConverter = new QueryStringConverter();
 }
示例#27
0
 public ReplyDispatchFormatter(OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
     : base(operation, endpoint, converter, behavior)
 {
 }
 public void Setup()
 {
     c = new QueryStringConverter();
 }
示例#29
0
        private void CheckNoUnmappedParameters(OperationDescription operationDescription, int jsonValuePosition)
        {
            string             uriTemplate = null;
            WebInvokeAttribute wia         = operationDescription.Behaviors.Find <WebInvokeAttribute>();
            MessagePartDescriptionCollection inputBodyParts = operationDescription.Messages[0].Body.Parts;

            if (wia != null)
            {
                uriTemplate = wia.UriTemplate;
            }

            // if uriTemplate == null, no parameters are bound to the template; JsonValue must be the only parameter in the operation
            if (uriTemplate != null)
            {
                UriTemplate template = new UriTemplate(uriTemplate);
                Dictionary <string, Type> operationParameters       = new Dictionary <string, Type>(StringComparer.OrdinalIgnoreCase);
                Dictionary <string, bool> mappedOperationParameters = new Dictionary <string, bool>(StringComparer.OrdinalIgnoreCase);
                for (int i = 0; i < inputBodyParts.Count; i++)
                {
                    if (i != jsonValuePosition)
                    {
                        operationParameters.Add(inputBodyParts[i].Name, inputBodyParts[i].Type);
                        mappedOperationParameters[inputBodyParts[i].Name] = false;
                    }
                }

                foreach (string pathVar in template.PathSegmentVariableNames)
                {
                    if (operationParameters.ContainsKey(pathVar))
                    {
                        mappedOperationParameters[pathVar] = true;
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new InvalidOperationException(
                                      DiagnosticUtility.GetString(
                                          SR.UriTemplateParameterNotInOperation,
                                          operationDescription.Name,
                                          operationDescription.DeclaringContract.Name,
                                          pathVar)));
                    }
                }

                QueryStringConverter qsc = this.GetQueryStringConverter(operationDescription);
                foreach (string queryVar in template.QueryValueVariableNames)
                {
                    if (operationParameters.ContainsKey(queryVar))
                    {
                        mappedOperationParameters[queryVar] = true;
                        if (!qsc.CanConvert(operationParameters[queryVar]))
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                      new InvalidOperationException(
                                          DiagnosticUtility.GetString(
                                              SR.QueryVariableCannotBeConverted,
                                              operationDescription.Name,
                                              operationDescription.DeclaringContract.Name,
                                              queryVar,
                                              operationParameters[queryVar].FullName,
                                              qsc.GetType().Name)));
                        }
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new InvalidOperationException(
                                      DiagnosticUtility.GetString(
                                          SR.UriTemplateParameterNotInOperation,
                                          operationDescription.Name,
                                          operationDescription.DeclaringContract.Name,
                                          queryVar)));
                    }
                }

                foreach (string paramName in mappedOperationParameters.Keys)
                {
                    if (!mappedOperationParameters[paramName])
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new InvalidOperationException(
                                      DiagnosticUtility.GetString(
                                          SR.ParameterUnmappedInUriTemplate,
                                          operationDescription.Name,
                                          operationDescription.DeclaringContract.Name)));
                    }
                }
            }
        }
 public MyFormUrlEncodedAwareFormatter(OperationDescription operation, IDispatchMessageFormatter originalFormatter, QueryStringConverter queryStringConverter)
 {
     this.operation            = operation;
     this.originalFormatter    = originalFormatter;
     this.queryStringConverter = queryStringConverter;
 }