Ejemplo n.º 1
0
        public static OAuthRequest GenerateConsumerRequest(OAuthConfig config, Uri requestUri, NameValueCollection requestParams, HttpMethods httpMethod)
        {
            if (config == null)
                throw new ArgumentNullException("config");
            if (requestUri == null)
                throw new ArgumentNullException("requestUri");
            if (requestParams == null)
                requestParams = new NameValueCollection();

            var request = new OAuthRequest();
            request.requestUri = requestUri;
            request.config = config;
            request.httpMethod = httpMethod;
            request.requestType = RequestTypes.ConsumerRequest;

            // Parse any existing URI Params
            request.ParseUriParams(requestUri, requestParams);

            // Assign request params
            request.requestParams = requestParams;

            // Setup required params
            request.requestParams[config.OAuthConsumerKeyKey] = config.OAuthConsumerKey;

            return request;
        }
Ejemplo n.º 2
0
 public Route(HttpMethods httpMethod, string endpoint, Action<RoutedHttpRequest, HttpListenerResponse> callback)
 {
     HttpMethod = httpMethod;
       Callback = callback;
       Endpoint = endpoint;
       Regex = BuildRegex(Endpoint);
 }
Ejemplo n.º 3
0
 public Request(Uri uri,string controllerName,string actionName,HttpMethods method= HttpMethods.All)
 {
     this.Uri = uri;
     this.ActionName = actionName;
     this.ControllerName = controllerName;
     this.Method = method;
 }
Ejemplo n.º 4
0
        public void AddCommand(string controllerName, string actionName,HttpMethods method, ICommand cmd)
        {
            SortedDictionary<string, Dictionary<HttpMethods, ICommand>> actions = null;
            if (!_Datas.TryGetValue(controllerName, out actions)) {
                actions = new SortedDictionary<string, Dictionary<HttpMethods, ICommand>>();
                _Datas.Add(controllerName,actions);
            }
            Dictionary<HttpMethods, ICommand> methods = null;
            if (!actions.TryGetValue(actionName, out methods)) {
                methods = new Dictionary<HttpMethods, ICommand>();
                actions.Add(actionName,methods);
            }
            if (((int)method & (int)HttpMethods.GET) > 0) {
                if (methods.ContainsKey(HttpMethods.GET)) methods[HttpMethods.GET] = cmd;
                else methods.Add(HttpMethods.GET,cmd);
            }

            if (((int)method & (int)HttpMethods.POST) > 0)
            {
                if (methods.ContainsKey(HttpMethods.POST)) methods[HttpMethods.POST] = cmd;
                else methods.Add(HttpMethods.POST, cmd);
            }

            if (((int)method & (int)HttpMethods.PUT) > 0)
            {
                if (methods.ContainsKey(HttpMethods.PUT)) methods[HttpMethods.PUT] = cmd;
                else methods.Add(HttpMethods.PUT, cmd);
            }

            if (((int)method & (int)HttpMethods.DELETE) > 0)
            {
                if (methods.ContainsKey(HttpMethods.DELETE)) methods[HttpMethods.DELETE] = cmd;
                else methods.Add(HttpMethods.DELETE, cmd);
            }
        }
Ejemplo n.º 5
0
            public void BetterReturnsTrueWhenTheMethodAndUrlAreTheSame(HttpMethods method1, string url1, 
                HttpMethods method2, string url2, bool expectedResult)
            {
                var request1 = new HttpRequest(method1, url1);
                var request2 = new HttpRequest(method2, url2);

                Assert.True(request1.Equals(request2) == expectedResult);
            }
Ejemplo n.º 6
0
 public HttpRequestV2(IHttpHeaders headers, HttpMethods method, string protocol, Uri uri, string[] requestParameters)
 {
     _headers = headers;
     _method = method;
     _protocol = protocol;
     _uri = uri;
     _requestParameters = requestParameters;
 }
Ejemplo n.º 7
0
            /// <summary>
            ///     Подписывает запрос
            /// </summary>
            /// <param name="httpMethod">
            ///     метод, используемый для запроса
            /// </param>
            /// <param name="requestUrl">
            ///     адрес для запроса
            /// </param>
            /// <param name="requestParameters">
            ///     параметры запроса
            /// </param>
            /// <param name="consumerInfo">
            ///     информация о программе клиенте
            /// </param>
            /// <param name="token">
            ///     токен
            /// </param>
            /// <exception cref="ArgumentNullException"></exception>
            /// <exception cref="ArgumentOutOfRangeException"></exception>
            /// <returns>
            ///     подписанная сторока запроса
            /// </returns>
            public static string Sign(HttpMethods httpMethod, string requestUrl,
                List<RequestParameter> requestParameters,
                ConsumerInfo consumerInfo,
                OAuthToken token)
            {
                if (consumerInfo.CallbackUrl == null && consumerInfo.ConsumerKey == null &&
                    consumerInfo.ConsumerSecret == null) throw new ArgumentNullException("consumerInfo");
                // Подготовка и нормализация операндов для подписи
                // Определяем метод запроса
                if ((httpMethod < 0) && (httpMethod > (HttpMethods) 3))
                    throw new ArgumentOutOfRangeException("httpMethod");
                var baseHttpMethod = httpMethod.ToString().ToUpper() + "&";
                // определяем и нормализуем Url запроса
                if (string.IsNullOrWhiteSpace(requestUrl)) throw new ArgumentNullException("requestUrl");
                var baseRequesUrl = Uri.EscapeDataString(requestUrl) + "&";
                // Определяем и нормализуем параметры запроса
                if (requestParameters == null) throw new ArgumentNullException("requestParameters");
                // нормализуем и сортируем список параметров
                requestParameters = NormalizeRequestParameters(requestParameters);

                var baseParameters = string.Join("&",
                    requestParameters.Select(param => param.Name + "=" + param.Value));
                //строка для подписывания
                var baseRequestString = baseHttpMethod + baseRequesUrl + Uri.EscapeDataString(baseParameters);
#if DEBUG
                Debug.WriteLine(string.Format("Подписываемая строка {0}", baseRequestString));
#endif
                // Определяем ключ для подписи
                var baseKey = token == null
                    ? consumerInfo.ConsumerSecret + "&" + string.Empty
                    : consumerInfo.ConsumerSecret + "&" + token.Secret;
                // осуществляем шифрование
                var encoder = new HMACSHA1 {Key = Encoding.ASCII.GetBytes(baseKey)};
                var buffer = Encoding.ASCII.GetBytes(baseRequestString);
                var signatureByte = encoder.ComputeHash(buffer, 0, buffer.Length);
                // получаем стороку подписи в представлении Base64
                var sigmature = Convert.ToBase64String(signatureByte);
#if DEBUG
                Debug.WriteLine(string.Format("Подписанная строка {0}", sigmature));
#endif

                /* Формируем подписанную строку запроса */

                // Для формирования стоки запроса к параметрам добавляем параметр с цифровой подписью
                requestParameters.Add(new RequestParameter(OAuthParam.Signature,
                    NormalizeParameter(sigmature)));
                // формируем строку
                var signedUrlString = requestUrl + "?" +
                                      string.Join("&", requestParameters.Select(param => param.Name + "=" + param.Value));
#if DEBUG
                Debug.WriteLine(string.Format("Подписанная строка запроса {0}", signedUrlString));
#endif

                // возвращаем подписанную строку
                return signedUrlString;
            }
Ejemplo n.º 8
0
        public static OAuthRequest GenerateProtectedRequest(OAuthConfig config, Uri requestUri, NameValueCollection requestParams, HttpMethods httpMethod)
        {
            var request = GenerateSignedRequest(config, requestUri, requestParams, httpMethod);

            request.requestParams[config.OAuthTokenKey] = config.OAuthToken;

            request.requestType = RequestTypes.ProtectedRequest;

            return request;
        }
        public WADLMethod(String methodName, HttpMethods method)
            : base()
        {
            this.name = methodName;
            this.method = method;

            this.queryType = QueryTypes.urlEncoded;
            this.parameters = new List<WADLParam>();
            this.headers = new List<WADLParam>();
            this.representations = new List<WADLRepresentation>(); 
        }
Ejemplo n.º 10
0
        public void Should_Get_Right_Method(HttpMethods method)
        {
            // Arrange
            var methodName = Enum.GetName(typeof(HttpMethods), method);
            var target = GetTarget();

            // Act
            var actual = target.Provide(methodName);

            // Assert
            actual.ToString().ShouldBe(methodName);
        }
Ejemplo n.º 11
0
            public async void DoesNotPersistRequestIfItAlreadyExists2(HttpMethods method, string url, int times)
            {
                var request = new HttpRequest { Method = HttpMethods.Get, Url = "http://localhost:3000/good" };

                var sqlite = new Mock<ISQLiteAsyncConnection>();
                sqlite.Setup(s => s.Get<HttpRequest>()).Returns(Task.FromResult(new List<HttpRequest> { request }));

                var newRequest = new HttpRequest { Method = method, Url = url };
                var requestHistory = new RequestHistory(sqlite.Object);
                await requestHistory.AddRequestAsync(newRequest);

                sqlite.Verify(s => s.InsertAsync(It.IsAny<HttpRequest>()), times.ToTimes());
            }
Ejemplo n.º 12
0
 public ICommand GetOrCreateCommand(RouteData routeData,HttpMethods method,Context context)
 {
     SortedDictionary<string, Dictionary<HttpMethods,ICommand>> actions = null;
     if (!_Datas.TryGetValue(routeData.ControllerName, out actions))
     {
         return null;
     }
     Dictionary<HttpMethods, ICommand> methods = null;
     if (!actions.TryGetValue(routeData.ActionName, out methods))
     {
         return null;
     }
     foreach (var pair in methods) {
         if (((int)pair.Key & (int)method) > 0) return pair.Value;
     }
     return null;
 }
Ejemplo n.º 13
0
        public PretendRequestInfo(string url, HttpMethods httpMethod = HttpMethods.Get, bool forPrinting = false, bool forSrcAttr = false)
        {
            HttpMethod = httpMethod;
            if (forPrinting)
                url = url.Replace("/bloom/", "/bloom/OriginalImages/");

            // In the real request, RawUrl does not include this prefix
            RawUrl = url.Replace(ServerBase.ServerUrl, "");

            // When JavaScript inserts a real path into the html it replaces the three magic html characters with these substitutes.
            // For this PretendRequestInfo we simulate that by doing the replace here in the url.
            if (forSrcAttr)
                url = EnhancedImageServer.SimulateJavaScriptHandlingOfHtml(url);

            // Reducing the /// emulates a behavior of the real HttpListener
            LocalPathWithoutQuery = url.Replace(ServerBase.ServerUrl, "").Replace("/bloom/OriginalImages///", "/bloom/OriginalImages/").Replace("/bloom///", "/bloom/").UnescapeCharsForHttp();
        }
 private HttpWebRequest CreateRequest(HttpMethods method)
 {
     var serializedPayload = Utility.SerializeParameters(_payload);
      var url = Driver.Instance.Url;
      if (UsesQueryString()) { url += '?' + serializedPayload; }
      var request = (HttpWebRequest)WebRequest.Create(url);
      request.Method = method.ToString().ToUpper();
     //         request.Headers["X-Mashape-Language"] = "dotnet";
     //         request.Headers["X-Mashape-Version"] = Communicator.Version;
     #if !WINDOWS_PHONE
      request.Timeout = 10000;
      request.ReadWriteTimeout = 10000;
      request.KeepAlive = false;
     #endif
      if (!UsesQueryString())
      {
     PayloadData = PreparePost(request, serializedPayload);
      }
      return request;
 }
Ejemplo n.º 15
0
 public static bool Is(this HttpMethods self, HttpMethods method) {
     return ((int)self & (int)method) != 0;
 }
Ejemplo n.º 16
0
        internal APIResponse Call(HttpMethods method, string path, object callParams)
        {
            string queryString = string.Empty;
            string content = string.Empty;

            if (method == HttpMethods.GET || method == HttpMethods.DELETE)
                queryString = ExtractQueryString(callParams);
            else if (method == HttpMethods.POST || method == HttpMethods.PUT)
                content = (new JsonTranslator()).Encode(callParams);

            string url = String.Format("{0}/{1}{2}",
                                                    this.State.ApiUrl,
                                                    path,
                                                    queryString);

            return Call(method, path, content, new HttpHelper(url));
        }
Ejemplo n.º 17
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="resource"></param>
 /// <param name="method"></param>
 /// <param name="ignoreRoot"></param>
 public RestRequest(string resource, HttpMethods method, bool ignoreRoot)
     : this(resource, method)
 {
     IgnoreRootElement = ignoreRoot;
 }
Ejemplo n.º 18
0
 // Matching is a bit weak in this demo.
 // It's written this way to satisfy both the composite gateway and website demos.
 public bool Matches(RouteData routeData, string httpMethod) =>
 HttpMethods.IsGet(httpMethod) &&
 string.Equals((string)routeData.Values["controller"], "orders", StringComparison.OrdinalIgnoreCase) &&
 routeData.Values.ContainsKey("id");
Ejemplo n.º 19
0
        internal APIResponse Call(HttpMethods method, string path, string content, HttpHelper httpHelper)
        {
            var request = httpHelper.HttpWebRequest;
            request.Method = method.ToString();

            request.ContentType = "application/json";
            request.Headers.Add("Authorization", "Bearer " + this.State.AccessToken);

            if ((method == HttpMethods.POST || method == HttpMethods.PUT) && !string.IsNullOrEmpty(content))
            {
                using (var writer = new StreamWriter(request.GetRequestStream()))
                {
                    writer.Write(content);
                    writer.Close();
                }
            }

            return GetResponse((HttpWebResponseWrapper)request.GetResponse());
        }
Ejemplo n.º 20
0
        /// <inheritdoc />
        public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            var request = context.HttpContext.Request;

            if (HttpMethods.IsPost(request.Method))
            {
                // 1. Confirm a secure connection.
                var errorResult = EnsureSecureConnection(ReceiverName, context.HttpContext.Request);
                if (errorResult != null)
                {
                    context.Result = errorResult;
                    return;
                }

                // 2. Get the expected hash from the signature header.
                var header = GetRequestHeader(request, DropboxConstants.SignatureHeaderName, out errorResult);
                if (errorResult != null)
                {
                    context.Result = errorResult;
                    return;
                }

                var expectedHash = FromHex(header, DropboxConstants.SignatureHeaderName);
                if (expectedHash == null)
                {
                    context.Result = CreateBadHexEncodingResult(DropboxConstants.SignatureHeaderName);
                    return;
                }

                // 3. Get the configured secret key.
                var secretKey = GetSecretKey(
                    ReceiverName,
                    context.RouteData,
                    DropboxConstants.SecretKeyMinLength,
                    DropboxConstants.SecretKeyMaxLength);
                if (secretKey == null)
                {
                    context.Result = new NotFoundResult();
                    return;
                }

                var secret = Encoding.UTF8.GetBytes(secretKey);

                // 4. Get the actual hash of the request body.
                var actualHash = await ComputeRequestBodySha256HashAsync(request, secret);

                // 5. Verify that the actual hash matches the expected hash.
                if (!SecretEqual(expectedHash, actualHash))
                {
                    // Log about the issue and short-circuit remainder of the pipeline.
                    errorResult = CreateBadSignatureResult(DropboxConstants.SignatureHeaderName);

                    context.Result = errorResult;
                    return;
                }
            }

            await next();
        }
Ejemplo n.º 21
0
 private static string?GetFuzzyMatchHttpMethod(PageContext context)
 {
     // Map HEAD to get.
     return(HttpMethods.IsHead(context.HttpContext.Request.Method) ? HttpMethods.Get : null);
 }
        /// <summary>
        /// For framework use only.
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="candidates"></param>
        /// <returns></returns>
        public Task ApplyAsync(HttpContext httpContext, CandidateSet candidates)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }

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

            // Returning a 405 here requires us to return keep track of all 'seen' HTTP methods. We allocate to
            // keep track of this beause we either need to keep track of the HTTP methods or keep track of the
            // endpoints - both allocate.
            //
            // Those code only runs in the presence of dynamic endpoints anyway.
            //
            // We want to return a 405 iff we eliminated ALL of the currently valid endpoints due to HTTP method
            // mismatch.
            bool?            needs405Endpoint = null;
            HashSet <string>?methods          = null;

            for (var i = 0; i < candidates.Count; i++)
            {
                // We do this check first for consistency with how 405 is implemented for the graph version
                // of this code. We still want to know if any endpoints in this set require an HTTP method
                // even if those endpoints are already invalid - hence the null-check.
                var metadata = candidates[i].Endpoint?.Metadata.GetMetadata <IHttpMethodMetadata>();
                if (metadata == null || metadata.HttpMethods.Count == 0)
                {
                    // Can match any method.
                    needs405Endpoint = false;
                    continue;
                }

                // Saw a valid endpoint.
                needs405Endpoint = needs405Endpoint ?? true;

                if (!candidates.IsValidCandidate(i))
                {
                    continue;
                }

                var httpMethod = httpContext.Request.Method;
                var headers    = httpContext.Request.Headers;
                if (metadata.AcceptCorsPreflight &&
                    HttpMethods.Equals(httpMethod, PreflightHttpMethod) &&
                    headers.ContainsKey(HeaderNames.Origin) &&
                    headers.TryGetValue(HeaderNames.AccessControlRequestMethod, out var accessControlRequestMethod) &&
                    !StringValues.IsNullOrEmpty(accessControlRequestMethod))
                {
                    needs405Endpoint = false; // We don't return a 405 for a CORS preflight request when the endpoints accept CORS preflight.
                    httpMethod       = accessControlRequestMethod;
                }

                var matched = false;
                for (var j = 0; j < metadata.HttpMethods.Count; j++)
                {
                    var candidateMethod = metadata.HttpMethods[j];
                    if (!HttpMethods.Equals(httpMethod, candidateMethod))
                    {
                        methods = methods ?? new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                        methods.Add(candidateMethod);
                        continue;
                    }

                    matched          = true;
                    needs405Endpoint = false;
                    break;
                }

                if (!matched)
                {
                    candidates.SetValidity(i, false);
                }
            }

            if (needs405Endpoint == true)
            {
                // We saw some endpoints coming in, and we eliminated them all.
                httpContext.SetEndpoint(CreateRejectionEndpoint(methods !.OrderBy(m => m, StringComparer.OrdinalIgnoreCase)));
                httpContext.Request.RouteValues = null !;
            }

            return(Task.CompletedTask);
        }
Ejemplo n.º 23
0
        /// <inheritdoc />
        public Task Invoke(HttpContext context, ICorsPolicyProvider corsPolicyProvider)
        {
            // CORS policy resolution rules:
            //
            // 1. If there is an endpoint with IDisableCorsAttribute then CORS is not run
            // 2. If there is an endpoint with ICorsPolicyMetadata then use its policy or if
            //    there is an endpoint with IEnableCorsAttribute that has a policy name then
            //    fetch policy by name, prioritizing it above policy on middleware
            // 3. If there is no policy on middleware then use name on middleware
            var endpoint = context.GetEndpoint();

            if (endpoint != null)
            {
                // EndpointRoutingMiddleware uses this flag to check if the CORS middleware processed CORS metadata on the endpoint.
                // The CORS middleware can only make this claim if it observes an actual endpoint.
                context.Items[CorsMiddlewareWithEndpointInvokedKey] = CorsMiddlewareWithEndpointInvokedValue;
            }

            if (!context.Request.Headers.ContainsKey(CorsConstants.Origin))
            {
                return(_next(context));
            }

            // Get the most significant CORS metadata for the endpoint
            // For backwards compatibility reasons this is then downcast to Enable/Disable metadata
            var corsMetadata = endpoint?.Metadata.GetMetadata <ICorsMetadata>();

            if (corsMetadata is IDisableCorsAttribute)
            {
                var isOptionsRequest = HttpMethods.IsOptions(context.Request.Method);

                var isCorsPreflightRequest = isOptionsRequest && context.Request.Headers.ContainsKey(CorsConstants.AccessControlRequestMethod);

                if (isCorsPreflightRequest)
                {
                    // If this is a preflight request, and we disallow CORS, complete the request
                    context.Response.StatusCode = StatusCodes.Status204NoContent;
                    return(Task.CompletedTask);
                }

                return(_next(context));
            }

            var corsPolicy = _policy;
            var policyName = _corsPolicyName;

            if (corsMetadata is ICorsPolicyMetadata corsPolicyMetadata)
            {
                policyName = null;
                corsPolicy = corsPolicyMetadata.Policy;
            }
            else if (corsMetadata is IEnableCorsAttribute enableCorsAttribute &&
                     enableCorsAttribute.PolicyName != null)
            {
                // If a policy name has been provided on the endpoint metadata then prioritizing it above the static middleware policy
                policyName = enableCorsAttribute.PolicyName;
                corsPolicy = null;
            }

            if (corsPolicy == null)
            {
                // Resolve policy by name if the local policy is not being used
                var policyTask = corsPolicyProvider.GetPolicyAsync(context, policyName);
                if (!policyTask.IsCompletedSuccessfully)
                {
                    return(InvokeCoreAwaited(context, policyTask));
                }

                corsPolicy = policyTask.Result;
            }

            return(EvaluateAndApplyPolicy(context, corsPolicy));

            async Task InvokeCoreAwaited(HttpContext context, Task <CorsPolicy?> policyTask)
            {
                var corsPolicy = await policyTask;

                await EvaluateAndApplyPolicy(context, corsPolicy);
            }
        }
Ejemplo n.º 24
0
        private bool SetupContent(object content, string contentMediaType, bool contentAsJson, bool contentUseCamelCase, HttpRequest request, HttpRequestMessage requestMessage, string requestMethod)
        {
            if (!HttpMethods.IsGet(requestMethod) && !HttpMethods.IsHead(requestMethod) && !HttpMethods.IsDelete(requestMethod) && !HttpMethods.IsTrace(requestMethod))
            {
                if (request.HasFormContentType)
                {
                    var dataToSend = content != null ? content as IFormCollection : request.Form;
                    requestMessage.Content = ToHttpContent(dataToSend, request.ContentType);
                    return(false);
                }
                else
                {
                    requestMessage.Content = content != null?CreateHttpContent(content, contentMediaType, contentAsJson, contentUseCamelCase) : new StreamContent(request.Body);
                }
            }

            return(true);
        }
Ejemplo n.º 25
0
 public async Task <Member> GetCurrentClient()
 {
     return(await HttpMethods <Member> .GetAsync(Client, "/currentClient"));
 }
        /// <inheritdoc />
        public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            var routeData = context.RouteData;
            var request   = context.HttpContext.Request;

            if (routeData.TryGetWebHookReceiverName(out var receiverName) &&
                IsApplicable(receiverName) &&
                HttpMethods.IsPost(request.Method))
            {
                // 1. Confirm a secure connection.
                var errorResult = EnsureSecureConnection(ReceiverName, context.HttpContext.Request);
                if (errorResult != null)
                {
                    context.Result = errorResult;
                    return;
                }

                // 2. Get the expected hash from the signature headers.
                var header = GetRequestHeader(request, PusherConstants.SignatureHeaderName, out errorResult);
                if (errorResult != null)
                {
                    context.Result = errorResult;
                    return;
                }

                var expectedHash = GetDecodedHash(header, PusherConstants.SignatureHeaderName, out errorResult);
                if (errorResult != null)
                {
                    context.Result = errorResult;
                    return;
                }

                // 3. Get the configured secret key.
                var secretKeys = GetSecretKeys(ReceiverName, routeData);
                if (!secretKeys.Exists())
                {
                    context.Result = new NotFoundResult();
                    return;
                }

                var applicationKey = GetRequestHeader(request, PusherConstants.SignatureKeyHeaderName, out errorResult);
                if (errorResult != null)
                {
                    context.Result = errorResult;
                    return;
                }

                var secretKey = secretKeys[applicationKey];
                if (secretKey == null ||
                    secretKey.Length < PusherConstants.SecretKeyMinLength ||
                    secretKey.Length > PusherConstants.SecretKeyMaxLength)
                {
                    Logger.LogError(
                        0,
                        "The '{HeaderName}' header value of '{HeaderValue}' is not recognized as a valid " +
                        "application key. Please ensure the correct application key / secret key pairs have " +
                        "been configured.",
                        PusherConstants.SignatureKeyHeaderName,
                        applicationKey);

                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        Resources.SignatureFilter_SecretNotFound,
                        PusherConstants.SignatureKeyHeaderName,
                        applicationKey);

                    context.Result = new BadRequestObjectResult(message);
                    return;
                }

                var secret = Encoding.UTF8.GetBytes(secretKey);

                // 4. Get the actual hash of the request body.
                var actualHash = await GetRequestBodyHash_SHA256(request, secret);

                // 5. Verify that the actual hash matches the expected hash.
                if (!SecretEqual(expectedHash, actualHash))
                {
                    // Log about the issue and short-circuit remainder of the pipeline.
                    errorResult = CreateBadSignatureResult(receiverName, PusherConstants.SignatureHeaderName);

                    context.Result = errorResult;
                    return;
                }
            }

            await next();
        }
Ejemplo n.º 27
0
 public ControllerMethod(Type controllerType, HttpMethods method)
 {
     _controllerType = controllerType;
     _method         = method;
 }
        public async Task Invoke(HttpContext context)
        {
            PathString subpath;

            if (!context.Request.Path.StartsWithSegments(_options.Path, out subpath))
            {
                await _next(context);

                return;
            }

            var policyName = subpath.ToUriComponent().Trim('/');

            if (policyName.Length == 0)
            {
                policyName = Constants.DefaultPolicy;
            }

            if (_options.AuthorizationPolicy != null)
            {
                var principal = await SecurityHelper.GetUserPrincipal(context, _options.AuthorizationPolicy);

                if (!await _authorizationService.AuthorizeAsync(principal, context, _options.AuthorizationPolicy))
                {
                    _logger.AuthorizationFailed();
                    await _next(context);

                    return;
                }
            }

            HealthCheckPolicy policy = _policyProvider.GetPolicy(policyName);

            if (policy == null)
            {
                _logger.InvalidPolicy(policyName);
                await _next(context);

                return;
            }

            var response            = context.Response;
            var healthCheckResponse = await _healthService.CheckHealthAsync(policy);

            if (healthCheckResponse.HasErrors)
            {
                _logger.HealthCheckFailed(healthCheckResponse.Errors);
                if (healthCheckResponse.HasCriticalErrors)
                {
                    response.StatusCode = StatusCodes.Status503ServiceUnavailable;
                    response.WriteRetryAfterHeader(healthCheckResponse.RetryAfter);
                }
            }
            else
            {
                _logger.HealthCheckSucceeded();
                response.StatusCode = StatusCodes.Status200OK;
            }

            if (_options.SendResults && !HttpMethods.IsHead(context.Request.Method))
            {
                response.ContentType = ApplicationJson;
                using (var writer = new HttpResponseStreamWriter(response.Body, Encoding.UTF8, 1024, _bytePool, _charPool))
                {
                    using (var jsonWriter = new JsonTextWriter(writer))
                    {
                        jsonWriter.ArrayPool   = _jsonCharPool;
                        jsonWriter.CloseOutput = false;

                        _jsonSerializer.Serialize(jsonWriter, healthCheckResponse.Results);
                    }
                }
            }
        }
        /// <summary>
        /// Make an HTTP Request to the Shopify API
        /// </summary>
        /// <param name="method">method to be used in the request</param>
        /// <param name="path">the path that should be requested</param>
        /// <param name="callParams">any parameters needed or expected by the API</param>
        /// <seealso cref="http://api.shopify.com/"/>
        /// <returns>the server response</returns>
        public object Call(HttpMethods method, string path, object callParams = null)
        {
            //NOTE: Shopify limits us to 2 calls per second
            var tickCount = DateTime.Now.Ticks;
            const int _minDelta = 750;
            if (_lastTickCount > 0)
            {
                var delta = (int)((tickCount - _lastTickCount) / TimeSpan.TicksPerMillisecond);
                if (delta < _minDelta)
                    System.Threading.Thread.Sleep(_minDelta - delta);
            }
            _lastTickCount = tickCount;
            string url = String.Format("https://{0}.myshopify.com/admin/{1}", State.ShopName, path);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = GetRequestContentType();
            request.Headers.Add("X-Shopify-Access-Token", this.State.AccessToken);
            request.Method = method.ToString();
            if (callParams != null)
            {
                if (method == HttpMethods.GET || method == HttpMethods.DELETE)
                {
                    // if no translator assume data is a query string
                    url = String.Format("{0}?{1}", url, callParams.ToString());

                    //// put params into query string
                    //StringBuilder queryString = new StringBuilder();
                    //foreach (string key in callParams.Keys)
                    //{
                    //    queryString.AppendFormat("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(callParams[key]));
                    //}
                }
                else if (method == HttpMethods.POST || method == HttpMethods.PUT)
                {
                    string requestBody;
                    // put params into post body
                    if (Translator == null)
                    {
                        //assume it's a string
                        requestBody = callParams.ToString();
                    }
                    else
                    {
                        requestBody = Translator.Encode(callParams);
                    }

                    //add the requst body to the request stream
                    if (!String.IsNullOrEmpty(requestBody))
                    {
                        using (var ms = new MemoryStream())
                        {
                            using (var writer = new StreamWriter(request.GetRequestStream()))
                            {
                                writer.Write(requestBody);
                                writer.Close();
                            }
                        }
                    }
                }
            }

            var response = (HttpWebResponse)request.GetResponse();
            string result = null;

            using (Stream stream = response.GetResponseStream())
            {
                StreamReader sr = new StreamReader(stream);
                result = sr.ReadToEnd();
                sr.Close();
            }

            //At least one endpoint will return an empty string, that we need to account for.
            if (string.IsNullOrWhiteSpace(result))
                return null;

            if (Translator != null)
                return Translator.Decode(result);

            return result;
        }
Ejemplo n.º 30
0
    public async Task Invoke(HttpContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        var request    = context.Request;
        var clientName = GetClient(request);

        if (string.IsNullOrEmpty(clientName))
        {
            // context.Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
            await this.next(context);

            return;
        }
        using (HttpClient client = this._clientFactory.CreateClient(clientName))
        {
            var requestMessage = new HttpRequestMessage();
            var requestMethod  = request.Method;
            if (!HttpMethods.IsGet(requestMethod) &&
                !HttpMethods.IsHead(requestMethod) &&
                !HttpMethods.IsDelete(requestMethod) &&
                !HttpMethods.IsTrace(requestMethod))
            {
                var streamContent = new StreamContent(request.Body);
                requestMessage.Content = streamContent;
            }

            // Copy the request headers
            foreach (var header in request.Headers)
            {
                if (!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()) && requestMessage.Content != null)
                {
                    requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
                }
            }

            requestMessage.RequestUri = new Uri($"{request.Path}{request.QueryString}", UriKind.Relative);
            requestMessage.Method     = new HttpMethod(request.Method);

            var response = await client.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead, context.RequestAborted);

            context.Response.StatusCode = (int)response.StatusCode;
            foreach (var header in response.Headers)
            {
                context.Response.Headers[header.Key] = header.Value.ToArray();
            }
            foreach (var header in response.Content.Headers)
            {
                context.Response.Headers[header.Key] = header.Value.ToArray();
            }

            // SendAsync removes chunking from the response. This removes the header so it doesn't expect a chunked response.
            context.Response.Headers.Remove("transfer-encoding");


            await response.Content.CopyToAsync(context.Response.Body);
        }
    }
 public RequestContext(HttpMethods method, IEnumerable<KeyValuePair<string, object>> payload)
 {
     _method = method;
      _payload = payload;
 }
Ejemplo n.º 32
0
        public static bool CheckSupportedWebSocketRequest(string method, IHeaderDictionary requestHeaders)
        {
            if (!HttpMethods.IsGet(method))
            {
                return(false);
            }

            var foundHeader = false;

            var values = requestHeaders.GetCommaSeparatedValues(HeaderNames.SecWebSocketVersion);

            foreach (var value in values)
            {
                if (string.Equals(value, Constants.Headers.SupportedVersion, StringComparison.OrdinalIgnoreCase))
                {
                    // WebSockets are long lived; so if the header values are valid we switch them out for the interned versions.
                    if (values.Length == 1)
                    {
                        requestHeaders.SecWebSocketVersion = Constants.Headers.SupportedVersion;
                    }
                    foundHeader = true;
                    break;
                }
            }
            if (!foundHeader)
            {
                return(false);
            }
            foundHeader = false;

            values = requestHeaders.GetCommaSeparatedValues(HeaderNames.Connection);
            foreach (var value in values)
            {
                if (string.Equals(value, HeaderNames.Upgrade, StringComparison.OrdinalIgnoreCase))
                {
                    // WebSockets are long lived; so if the header values are valid we switch them out for the interned versions.
                    if (values.Length == 1)
                    {
                        requestHeaders.Connection = HeaderNames.Upgrade;
                    }
                    foundHeader = true;
                    break;
                }
            }
            if (!foundHeader)
            {
                return(false);
            }
            foundHeader = false;

            values = requestHeaders.GetCommaSeparatedValues(HeaderNames.Upgrade);
            foreach (var value in values)
            {
                if (string.Equals(value, Constants.Headers.UpgradeWebSocket, StringComparison.OrdinalIgnoreCase))
                {
                    // WebSockets are long lived; so if the header values are valid we switch them out for the interned versions.
                    if (values.Length == 1)
                    {
                        requestHeaders.Upgrade = Constants.Headers.UpgradeWebSocket;
                    }
                    foundHeader = true;
                    break;
                }
            }
            if (!foundHeader)
            {
                return(false);
            }

            return(HandshakeHelpers.IsRequestKeyValid(requestHeaders.SecWebSocketKey.ToString()));
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Make an HTTP Request to the Haravan API
        /// </summary>
        /// <param name="method">method to be used in the request</param>
        /// <param name="path">the path that should be requested</param>
        /// <param name="callParams">any parameters needed or expected by the API</param>
        /// <seealso cref="http://api.haravan.com/"/>
        /// <returns>the server response</returns>
        public object Call(HttpMethods method, string path, object callParams)
        {
            string         url     = String.Format("https://{0}.myharavan.com{1}", State.ShopName, path);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.ContentType = GetRequestContentType();
            request.Headers.Add("Authorization", "bearer " + this.State.AccessToken);
            request.Method = method.ToString();
            if (callParams != null)
            {
                if (method == HttpMethods.GET || method == HttpMethods.DELETE)
                {
                    // if no translator assume data is a query string
                    url = String.Format("{0}?{1}", url, callParams.ToString());

                    //// put params into query string
                    //StringBuilder queryString = new StringBuilder();
                    //foreach (string key in callParams.Keys)
                    //{
                    //    queryString.AppendFormat("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(callParams[key]));
                    //}
                }
                else if (method == HttpMethods.POST || method == HttpMethods.PUT)
                {
                    string requestBody;
                    // put params into post body
                    if (Translator == null)
                    {
                        //assume it's a string
                        requestBody = callParams.ToString();
                    }
                    else
                    {
                        requestBody = Translator.Encode(callParams);
                    }

                    //add the requst body to the request stream
                    if (!String.IsNullOrEmpty(requestBody))
                    {
                        using (var ms = new MemoryStream())
                        {
                            using (var writer = new StreamWriter(request.GetRequestStream()))
                            {
                                writer.Write(requestBody);
                                writer.Close();
                            }
                        }
                    }
                }
            }

            var    response = (HttpWebResponse)request.GetResponse();
            string result   = null;

            using (Stream stream = response.GetResponseStream())
            {
                StreamReader sr = new StreamReader(stream);
                result = sr.ReadToEnd();
                sr.Close();
            }

            //At least one endpoint will return an empty string, that we need to account for.
            if (string.IsNullOrWhiteSpace(result))
            {
                return(null);
            }

            if (Translator != null)
            {
                return(Translator.Decode(result));
            }

            return(result);
        }
Ejemplo n.º 34
0
 public WeChatResult GetAccessToken(string WeChatId, string WeChatAppSecret, string testFlag, AccessTokenType TokenType)
 {
     try
     {
         var tokeninfo          = "";
         var JsonFileName       = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\" + "WeChatToken.json";
         var DateNow            = DateTime.Now;
         var IsHasRedis         = new RedisHelper().Ping();
         var IsHasTokenJsonFile = false;
         var TokenJsonStr       = "";
         #region 1、有Redis服务器,内存读取;2、无Redis服务器,文件流
         if (IsHasRedis)
         {
             TokenJsonStr = new RedisHelper().getValue(testFlag + "NormalWeChatToken");
         }
         else
         {
             IsHasTokenJsonFile = FileHelper.IsExistFile(JsonFileName);
             if (IsHasTokenJsonFile)
             {
                 TokenJsonStr = File.ReadAllText(JsonFileName);
             }
         }
         #endregion
         //1、token服务器不存在,首次创建;2、token服务器存在判断是否过期,过期则重新获取,未过期则直接使用
         var             IsNeedUpdateToken = true;
         List <TokenDef> listToken         = new List <TokenDef>();
         TokenDef        modelToken        = null;
         #region 取得已存储Token
         if (!string.IsNullOrEmpty(TokenJsonStr))
         {
             listToken  = JsonConvert.DeserializeObject <List <TokenDef> >(TokenJsonStr);
             modelToken = listToken.Where(x => x.TokenType == TokenType && x.WeChatId == WeChatId).FirstOrDefault();
         }
         if (modelToken != null)
         {
             if ((DateNow - modelToken.EndTime).Seconds < 0)
             {
                 IsNeedUpdateToken = false;
                 tokeninfo         = modelToken.AccessToken;
             }
         }
         #endregion
         if (IsNeedUpdateToken)
         {
             #region 获取新Token
             string url   = "https://api.weixin.qq.com/cgi-bin/token";
             string data  = "grant_type=client_credential&appid=" + WeChatId + "&secret=" + WeChatAppSecret + "";
             var    token = HttpMethods.HttpPost(url, data);
             if (string.IsNullOrEmpty(token))
             {
                 return new WeChatResult()
                        {
                            IsSuccess = false, Msg = "Token请求失败"
                        }
             }
             ;
             List <Info> jobInfoList = JsonConvert.DeserializeObject <List <Info> >("[" + token + "]");
             if (jobInfoList.Count > 0)
             {
                 tokeninfo = jobInfoList[0].access_token;
             }
             else
             {
                 return new WeChatResult()
                        {
                            IsSuccess = false, Msg = "Token请求失败"
                        }
             };
             if (modelToken == null)
             {
                 listToken.Add(new TokenDef()
                 {
                     WeChatId    = WeChatId,
                     TokenType   = TokenType,
                     AccessToken = tokeninfo,
                     StartTime   = DateNow,
                     EndTime     = DateNow.AddHours(1)
                 });
             }
             else
             {
                 foreach (var item in listToken)
                 {
                     if (item.WeChatId == WeChatId && TokenType == item.TokenType)
                     {
                         item.StartTime   = DateNow;
                         item.EndTime     = DateNow.AddHours(1);
                         item.AccessToken = tokeninfo;
                     }
                 }
             }
             #endregion
             #region 存储新Token
             var newJsonToken = JsonConvert.SerializeObject(listToken);
             if (IsHasRedis)
             {
                 new RedisHelper().setValue(testFlag + "NormalWeChatToken", newJsonToken);
             }
             else
             {
                 if (!IsHasTokenJsonFile)
                 {
                     FileHelper.CreateFile(JsonFileName);
                 }
                 File.WriteAllText(JsonFileName, newJsonToken);
             }
             #endregion
         }
         return(new WeChatResult()
         {
             IsSuccess = true, Msg = tokeninfo
         });
     }
     catch (Exception ex)
     {
         return(new WeChatResult()
         {
             IsSuccess = false, Msg = "Token请求失败"
         });
     }
 }
Ejemplo n.º 35
0
 private bool IsVoyagerRequest(HttpRequest httpRequest)
 => HttpMethods.IsGet(httpRequest.Method) && httpRequest.Path.StartsWithSegments(_options.Path);
Ejemplo n.º 36
0
        public async Task Invoke(HttpContext httpContext)
        {
            if (!string.Equals(_pairingToken, httpContext.Request.Headers[MSAspNetCoreToken], StringComparison.Ordinal))
            {
                _logger.LogError($"'{MSAspNetCoreToken}' does not match the expected pairing token '{_pairingToken}', request rejected.");
                httpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
                return;
            }

            // Handle shutdown from ANCM
            if (HttpMethods.IsPost(httpContext.Request.Method) &&
                httpContext.Request.Path.Equals(ANCMRequestPath) &&
                string.Equals(ANCMShutdownEventHeaderValue, httpContext.Request.Headers[MSAspNetCoreEvent], StringComparison.OrdinalIgnoreCase))
            {
                // Execute shutdown task on background thread without waiting for completion
                var shutdownTask = Task.Run(() => _applicationLifetime.StopApplication());
                httpContext.Response.StatusCode = StatusCodes.Status202Accepted;
                return;
            }

            if (Debugger.IsAttached && string.Equals("DEBUG", httpContext.Request.Method, StringComparison.OrdinalIgnoreCase))
            {
                // The Visual Studio debugger tooling sends a DEBUG request to make IIS & AspNetCoreModule launch the process
                // so the debugger can attach. Filter out this request from the app.
                return;
            }

            var bodySizeFeature = httpContext.Features.Get <IHttpMaxRequestBodySizeFeature>();

            if (bodySizeFeature != null && !bodySizeFeature.IsReadOnly)
            {
                // IIS already limits this, no need to do it twice.
                bodySizeFeature.MaxRequestBodySize = null;
            }

            if (_options.ForwardClientCertificate)
            {
                var header = httpContext.Request.Headers[MSAspNetCoreClientCert];
                if (!StringValues.IsNullOrEmpty(header))
                {
                    httpContext.Features.Set <ITlsConnectionFeature>(new ForwardedTlsConnectionFeature(_logger, header));
                }
            }

            if (_options.ForwardWindowsAuthentication)
            {
                // We must always process and clean up the windows identity, even if we don't assign the User.
                var user = GetUser(httpContext);
                if (user != null)
                {
                    // Flow it through to the authentication handler.
                    httpContext.Features.Set(user);

                    if (_options.AutomaticAuthentication)
                    {
                        httpContext.User = user;
                    }
                }
            }

            // Remove the upgrade feature if websockets are not supported by ANCM.
            // The feature must be removed on a per request basis as the Upgrade feature exists per request.
            if (!_isWebsocketsSupported)
            {
                httpContext.Features.Set <IHttpUpgradeFeature>(null);
            }

            await _next(httpContext);
        }
Ejemplo n.º 37
0
 public HttpRequest(HttpMethods method, string url)
 {
     Method = method;
     Url = url;
 }
Ejemplo n.º 38
0
    private StreamCopyHttpContent?SetupRequestBodyCopy(HttpRequest request, bool isStreamingRequest, ActivityCancellationTokenSource activityToken)
    {
        // If we generate an HttpContent without a Content-Length then for HTTP/1.1 HttpClient will add a Transfer-Encoding: chunked header
        // even if it's a GET request. Some servers reject requests containing a Transfer-Encoding header if they're not expecting a body.
        // Try to be as specific as possible about the client's intent to send a body. The one thing we don't want to do is to start
        // reading the body early because that has side-effects like 100-continue.
        var hasBody       = true;
        var contentLength = request.Headers.ContentLength;
        var method        = request.Method;

        var canHaveBodyFeature = request.HttpContext.Features.Get <IHttpRequestBodyDetectionFeature>();

        if (canHaveBodyFeature is not null)
        {
            // 5.0 servers provide a definitive answer for us.
            hasBody = canHaveBodyFeature.CanHaveBody;
        }
        // https://tools.ietf.org/html/rfc7230#section-3.3.3
        // All HTTP/1.1 requests should have Transfer-Encoding or Content-Length.
        // Http.Sys/IIS will even add a Transfer-Encoding header to HTTP/2 requests with bodies for back-compat.
        // HTTP/1.0 Connection: close bodies are only allowed on responses, not requests.
        // https://tools.ietf.org/html/rfc1945#section-7.2.2
        //
        // Transfer-Encoding overrides Content-Length per spec
        else if (request.Headers.TryGetValue(HeaderNames.TransferEncoding, out var transferEncoding) &&
                 transferEncoding.Count == 1 &&
                 string.Equals("chunked", transferEncoding.ToString(), StringComparison.OrdinalIgnoreCase))
        {
            hasBody = true;
        }
        else if (contentLength.HasValue)
        {
            hasBody = contentLength > 0;
        }
        // Kestrel HTTP/2: There are no required headers that indicate if there is a request body so we need to sniff other fields.
        else if (!ProtocolHelper.IsHttp2OrGreater(request.Protocol))
        {
            hasBody = false;
        }
        // https://tools.ietf.org/html/rfc7231#section-4.3.1
        // A payload within a GET/HEAD/DELETE/CONNECT request message has no defined semantics; sending a payload body on a
        // GET/HEAD/DELETE/CONNECT request might cause some existing implementations to reject the request.
        // https://tools.ietf.org/html/rfc7231#section-4.3.8
        // A client MUST NOT send a message body in a TRACE request.
        else if (HttpMethods.IsGet(method) ||
                 HttpMethods.IsHead(method) ||
                 HttpMethods.IsDelete(method) ||
                 HttpMethods.IsConnect(method) ||
                 HttpMethods.IsTrace(method))
        {
            hasBody = false;
        }
        // else hasBody defaults to true

        if (hasBody)
        {
            if (isStreamingRequest)
            {
                DisableMinRequestBodyDataRateAndMaxRequestBodySize(request.HttpContext);
            }

            // Note on `autoFlushHttpClientOutgoingStream: isStreamingRequest`:
            // The.NET Core HttpClient stack keeps its own buffers on top of the underlying outgoing connection socket.
            // We flush those buffers down to the socket on every write when this is set,
            // but it does NOT result in calls to flush on the underlying socket.
            // This is necessary because we proxy http2 transparently,
            // and we are deliberately unaware of packet structure used e.g. in gRPC duplex channels.
            // Because the sockets aren't flushed, the perf impact of this choice is expected to be small.
            // Future: It may be wise to set this to true for *all* http2 incoming requests,
            // but for now, out of an abundance of caution, we only do it for requests that look like gRPC.
            return(new StreamCopyHttpContent(
                       request: request,
                       autoFlushHttpClientOutgoingStream: isStreamingRequest,
                       clock: _clock,
                       activityToken));
        }

        return(null);
    }
Ejemplo n.º 39
0
 private APIResponse Call(HttpMethods method, string path)
 {
     return Call(method, path, null);
 }
Ejemplo n.º 40
0
 public ListItemsAttribute(string url, HttpMethods type)
 {
     this.Url = url;
     this.Type = type;
 }
Ejemplo n.º 41
0
 /// <summary>
 /// Creates a new RestRequest instance for a given Resource and Method.
 /// </summary>
 /// <param name="resource">The specific resource to access.</param>
 /// <param name="method">The HTTP method to use for the request.</param>
 public RestRequest(string resource, HttpMethods method)
     : this()
 {
     Method = method;
     Resource = resource;
 }
Ejemplo n.º 42
0
        /// <summary>
        /// Make an HTTP Request to the Shopify API
        /// </summary>
        /// <param name="method">method to be used in the request</param>
        /// <param name="path">the path that should be requested</param>
        /// <param name="callParams">any parameters needed or expected by the API</param>
        /// <seealso cref="http://api.shopify.com/"/>
        /// <returns>the server response</returns>
        public object Call(HttpMethods method, string path, object callParams)
        {
            string url = String.Format("https://{0}.myshopify.com{1}", State.ShopName, path);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = GetRequestContentType();
            request.Headers.Add("X-Shopify-Access-Token", this.State.AccessToken);
            request.Method = method.ToString();
            if (callParams != null)
            {
                if (method == HttpMethods.GET || method == HttpMethods.DELETE)
                {
                    // if no translator assume data is a query string
                    url = String.Format("{0}?{1}", url, callParams.ToString());

                    //// put params into query string
                    //StringBuilder queryString = new StringBuilder();
                    //foreach (string key in callParams.Keys)
                    //{
                    //    queryString.AppendFormat("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(callParams[key]));
                    //}
                }
                else if (method == HttpMethods.POST || method == HttpMethods.PUT)
                {
                    string requestBody;
                    // put params into post body
                    if (Translator == null)
                    {
                        //assume it's a string
                        requestBody = callParams.ToString();
                    }
                    else
                    {
                        requestBody = Translator.Encode(callParams);
                    }

                    //add the requst body to the request stream
                    if (!String.IsNullOrEmpty(requestBody))
                    {
                        using (var ms = new MemoryStream())
                        {
                            using (var writer = new StreamWriter(request.GetRequestStream()))
                            {
                                writer.Write(requestBody);
                                writer.Close();
                            }
                        }
                    }
                }
            }

            var response = (HttpWebResponse)request.GetResponse();
            string result = null;

            using (Stream stream = response.GetResponseStream())
            {
                StreamReader sr = new StreamReader(stream);
                result = sr.ReadToEnd();
                sr.Close();
            }

            if (Translator != null)
                return Translator.Decode(result);

            return result;

        }
Ejemplo n.º 43
0
 public ApiActionAttributes(string action, HttpMethods method)
 {
     Action = action;
     Method = method;
 }
Ejemplo n.º 44
0
 public HttpRequest(IHttpHeaders headers, HttpMethods method, string protocol, Uri uri, string[] requestParameters, IHttpHeaders queryString, IHttpPost post)
 {
     _headers = headers;
     _method = method;
     _protocol = protocol;
     _uri = uri;
     _requestParameters = requestParameters;
     _queryString = queryString;
     _post = post;
 }
Ejemplo n.º 45
0
 public EntityLink CreateEntityLink(IUrlHelper urlHelper, string routeName, int Id, HttpMethods Method = HttpMethods.Get)
 {
     return
         (new EntityLink()
     {
         Method = Method.ToString(),
         Rel = "self",
         Href = new Uri(urlHelper.Link(routeName, new { id = Id }))
     });
 }
Ejemplo n.º 46
0
        /// <summary>
        /// The invoke.
        /// </summary>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public async Task HandleHttpRequest(HttpContext context)
        {
            var httpClient = new HttpClient(new HttpClientHandler()
            {
                AllowAutoRedirect = false
            });
            var requestMessage = new HttpRequestMessage();
            var requestMethod  = context.Request.Method;

            if (!HttpMethods.IsGet(requestMethod) && !HttpMethods.IsHead(requestMethod) &&
                !HttpMethods.IsDelete(requestMethod) && !HttpMethods.IsTrace(requestMethod))
            {
                var streamContent = new StreamContent(context.Request.Body);
                requestMessage.Content = streamContent;
            }
            foreach (var header in context.Request.Headers)
            {
                if (!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()))
                {
                    requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
                }
            }

            if (!requestMessage.Headers.Any(x => x.Key == this.buffer.Configuration["HeaderName"]))
            {
                requestMessage.Headers.Add(
                    this.buffer.Configuration["HeaderName"],
                    @"Bearer " + (string)context.Items[RequestOptions.AccessToken]);
            }

            requestMessage.Headers.Host = ((Uri)context.Items[RequestOptions.TunnelUrl]).Host + ":"
                                          + ((Uri)context.Items[RequestOptions.TunnelUrl]).Port;
            requestMessage.RequestUri = ((Uri)context.Items[RequestOptions.TunnelUrl]);
            requestMessage.Method     = new HttpMethod(context.Request.Method);
            using (var responseMessage = await httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead))
            {
                var statusCode = (int)responseMessage.StatusCode;

                context.Response.StatusCode = statusCode;
                foreach (var header in responseMessage.Headers)
                {
                    context.Response.Headers[header.Key] = new StringValues(header.Value.ToArray());
                }

                foreach (var header in responseMessage.Content.Headers)
                {
                    context.Response.Headers[header.Key] = header.Value.FirstOrDefault();
                }

                context.Response.Headers.Remove("transfer-encoding");

                // Check if there is a redirect - could be with status code 3xx or 201
                if (responseMessage.Headers.Location != null)
                {
                    var location = context.Items["ServiceOriginPattern"] + responseMessage.Headers.Location.ToString();
                    context.Response.Headers["Location"] = new StringValues(new string[] { location });
                }

                if (statusCode != StatusCodes.Status401Unauthorized && statusCode != StatusCodes.Status403Forbidden)
                {
                    await responseMessage.Content.CopyToAsync(context.Response.Body);
                }
            }
        }
Ejemplo n.º 47
0
        public async Task InvokeAsync(HttpContext context)
        {
            if (context.WebSockets.IsWebSocketRequest)
            {
                await _next(context);

                return;
            }

            // Handle requests as per recommendation at http://graphql.org/learn/serving-over-http/
            // Inspiration: https://github.com/graphql/express-graphql/blob/master/src/index.js
            var httpRequest  = context.Request;
            var httpResponse = context.Response;

            var writer            = context.RequestServices.GetRequiredService <IDocumentWriter>();
            var cancellationToken = GetCancellationToken(context);

            // GraphQL HTTP only supports GET and POST methods
            bool isGet  = HttpMethods.IsGet(httpRequest.Method);
            bool isPost = HttpMethods.IsPost(httpRequest.Method);

            if (!isGet && !isPost)
            {
                httpResponse.Headers["Allow"] = "GET, POST";
                await WriteErrorResponseAsync(httpResponse, writer, cancellationToken,
                                              $"Invalid HTTP method. Only GET and POST are supported. {DOCS_URL}",
                                              httpStatusCode : 405 // Method Not Allowed
                                              );

                return;
            }

            // Parse POST body
            GraphQLRequest bodyGQLRequest = null;

            GraphQLRequest[] bodyGQLBatchRequest = null;
            if (isPost)
            {
                if (!MediaTypeHeaderValue.TryParse(httpRequest.ContentType, out var mediaTypeHeader))
                {
                    await WriteErrorResponseAsync(httpResponse, writer, cancellationToken, $"Invalid 'Content-Type' header: value '{httpRequest.ContentType}' could not be parsed.");

                    return;
                }

                switch (mediaTypeHeader.MediaType)
                {
                case MediaType.JSON:
                    var deserializationResult = await _deserializer.DeserializeFromJsonBodyAsync(httpRequest, cancellationToken);

                    if (!deserializationResult.IsSuccessful)
                    {
                        await WriteErrorResponseAsync(httpResponse, writer, cancellationToken, "Body text could not be parsed. Body text should start with '{' for normal graphql query or with '[' for batched query.");

                        return;
                    }
                    bodyGQLRequest      = deserializationResult.Single;
                    bodyGQLBatchRequest = deserializationResult.Batch;
                    break;

                case MediaType.GRAPH_QL:
                    bodyGQLRequest = await DeserializeFromGraphBodyAsync(httpRequest.Body);

                    break;

                case MediaType.FORM:
                    var formCollection = await httpRequest.ReadFormAsync();

                    bodyGQLRequest = DeserializeFromFormBody(formCollection);
                    break;

                default:
                    await WriteErrorResponseAsync(httpResponse, writer, cancellationToken, $"Invalid 'Content-Type' header: non-supported media type. Must be of '{MediaType.JSON}', '{MediaType.GRAPH_QL}' or '{MediaType.FORM}'. {DOCS_URL}");

                    return;
                }
            }

            // If we don't have a batch request, parse the query from URL too to determine the actual request to run.
            // Query string params take priority.
            GraphQLRequest gqlRequest = null;

            if (bodyGQLBatchRequest == null)
            {
                var urlGQLRequest = DeserializeFromQueryString(httpRequest.Query);

                gqlRequest = new GraphQLRequest
                {
                    Query         = urlGQLRequest.Query ?? bodyGQLRequest?.Query,
                    Inputs        = urlGQLRequest.Inputs ?? bodyGQLRequest?.Inputs,
                    Extensions    = urlGQLRequest.Extensions ?? bodyGQLRequest?.Extensions,
                    OperationName = urlGQLRequest.OperationName ?? bodyGQLRequest?.OperationName
                };
            }

            // Prepare context and execute
            var userContextBuilder = context.RequestServices.GetService <IUserContextBuilder>();
            var userContext        = userContextBuilder == null
                ? new Dictionary <string, object>() // in order to allow resolvers to exchange their state through this object
                : await userContextBuilder.BuildUserContext(context);

            var executer = context.RequestServices.GetRequiredService <IGraphQLExecuter <TSchema> >();

            // Normal execution with single graphql request
            if (bodyGQLBatchRequest == null)
            {
                var stopwatch = ValueStopwatch.StartNew();
                await RequestExecutingAsync(gqlRequest);

                var result = await ExecuteRequestAsync(gqlRequest, userContext, executer, context.RequestServices, cancellationToken);

                await RequestExecutedAsync(new GraphQLRequestExecutionResult(gqlRequest, result, stopwatch.Elapsed));

                await WriteResponseAsync(httpResponse, writer, cancellationToken, result);
            }
            // Execute multiple graphql requests in one batch
            else
            {
                var executionResults = new ExecutionResult[bodyGQLBatchRequest.Length];
                for (int i = 0; i < bodyGQLBatchRequest.Length; ++i)
                {
                    var gqlRequestInBatch = bodyGQLBatchRequest[i];

                    var stopwatch = ValueStopwatch.StartNew();
                    await RequestExecutingAsync(gqlRequestInBatch, i);

                    var result = await ExecuteRequestAsync(gqlRequestInBatch, userContext, executer, context.RequestServices, cancellationToken);

                    await RequestExecutedAsync(new GraphQLRequestExecutionResult(gqlRequestInBatch, result, stopwatch.Elapsed, i));

                    executionResults[i] = result;
                }

                await WriteResponseAsync(httpResponse, writer, cancellationToken, executionResults);
            }
        }
Ejemplo n.º 48
0
        public async Task <IEndpointResult> ProcessAsync(HttpContext context)
        {
            _logger.LogDebug($"Starting token request");

            NameValueCollection values;

            if (HttpMethods.IsPost(context.Request.Method))
            {
                if (!context.Request.HasFormContentType)
                {
                    _logger.LogDebug($"Unsupported media type");
                    return(new StatusCodeResult(HttpStatusCode.UnsupportedMediaType));
                }

                values = context.Request.Form.AsNameValueCollection();
            }
            else
            {
                _logger.LogDebug($"Method not allowed");
                return(new StatusCodeResult(HttpStatusCode.MethodNotAllowed));
            }

            var clientResult = await _clientValidator.ValidateAsync(context);

            if (clientResult.Client == null)
            {
                _logger.LogDebug($"Invalid client");
                return(VCResponseHelpers.Error(OidcConstants.TokenErrors.InvalidClient));
            }

            var grantType = values.Get(IdentityConstants.GrantTypeParameterName);

            if (string.IsNullOrEmpty(grantType))
            {
                _logger.LogDebug($"Invalid grant type of : {grantType}");
                return(VCResponseHelpers.Error(IdentityConstants.InvalidGrantTypeError));
            }

            var sessionId = values.Get(IdentityConstants.AuthorizationCodeParameterName);

            if (string.IsNullOrEmpty(sessionId))
            {
                _logger.LogDebug($"Invalid authorization code : {sessionId}");
                return(VCResponseHelpers.Error(IdentityConstants.InvalidAuthorizationCodeError));
            }

            var session = await _sessionStore.FindBySessionIdAsync(sessionId);

            if (session == null)
            {
                _logger.LogDebug($"Invalid session : {sessionId}");
                return(VCResponseHelpers.Error(IdentityConstants.InvalidSessionError, $"Cannot find stored session"));
            }

            if (session.PresentationRequestSatisfied == false)
            {
                _logger.LogDebug($"Presentation not satisfied, session id : {sessionId}");
                return(VCResponseHelpers.Error(IdentityConstants.InvalidSessionError, "Presentation request wasn't satisfied"));
            }

            try
            {
                _logger.LogDebug($"Constructing token result for session : {sessionId}");
                return(new TokenEndpointResult(session, _tokenIssuerService, _presentationConfigurationService, _sessionStore, _logger));
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Failed to create a token response");
                return(VCResponseHelpers.Error(IdentityConstants.GeneralError, "Failed to create a token"));
            }
        }
Ejemplo n.º 49
0
        private async Task <bool> InvokeUserinfoEndpointAsync()
        {
            OpenIdConnectRequest request;

            if (HttpMethods.IsGet(Request.Method))
            {
                request = new OpenIdConnectRequest(Request.Query);
            }

            else if (HttpMethods.IsPost(Request.Method))
            {
                // Note: if no Content-Type header was specified, assume the userinfo request
                // doesn't contain any parameter and create an empty OpenIdConnectRequest.
                if (string.IsNullOrEmpty(Request.ContentType))
                {
                    request = new OpenIdConnectRequest();
                }

                else
                {
                    // May have media/type; charset=utf-8, allow partial match.
                    if (!Request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
                    {
                        Logger.LogError("The userinfo request was rejected because an invalid 'Content-Type' " +
                                        "header was specified: {ContentType}.", Request.ContentType);

                        return(await SendUserinfoResponseAsync(new OpenIdConnectResponse
                        {
                            Error = OpenIdConnectConstants.Errors.InvalidRequest,
                            ErrorDescription = "The specified 'Content-Type' header is not valid."
                        }));
                    }

                    request = new OpenIdConnectRequest(await Request.ReadFormAsync());
                }
            }

            else
            {
                Logger.LogError("The userinfo request was rejected because an invalid " +
                                "HTTP method was specified: {Method}.", Request.Method);

                return(await SendUserinfoResponseAsync(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidRequest,
                    ErrorDescription = "The specified HTTP method is not valid."
                }));
            }

            // Note: set the message type before invoking the ExtractUserinfoRequest event.
            request.SetProperty(OpenIdConnectConstants.Properties.MessageType,
                                OpenIdConnectConstants.MessageTypes.UserinfoRequest);

            // Insert the userinfo request in the ASP.NET context.
            Context.SetOpenIdConnectRequest(request);

            var @event = new ExtractUserinfoRequestContext(Context, Scheme, Options, request);
            await Provider.ExtractUserinfoRequest(@event);

            if (@event.Result != null)
            {
                if (@event.Result.Handled)
                {
                    Logger.LogDebug("The userinfo request was handled in user code.");

                    return(true);
                }

                else if (@event.Result.Skipped)
                {
                    Logger.LogDebug("The default userinfo request handling was skipped from user code.");

                    return(false);
                }
            }

            else if (@event.IsRejected)
            {
                Logger.LogError("The userinfo request was rejected with the following error: {Error} ; {Description}",
                                /* Error: */ @event.Error ?? OpenIdConnectConstants.Errors.InvalidRequest,
                                /* Description: */ @event.ErrorDescription);

                return(await SendUserinfoResponseAsync(new OpenIdConnectResponse
                {
                    Error = @event.Error ?? OpenIdConnectConstants.Errors.InvalidRequest,
                    ErrorDescription = @event.ErrorDescription,
                    ErrorUri = @event.ErrorUri
                }));
            }

            Logger.LogInformation("The userinfo request was successfully extracted " +
                                  "from the HTTP request: {Request}.", request);

            string token = null;

            if (!string.IsNullOrEmpty(request.AccessToken))
            {
                token = request.AccessToken;
            }

            else
            {
                string header = Request.Headers[HeaderNames.Authorization];
                if (!string.IsNullOrEmpty(header))
                {
                    if (!header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
                    {
                        Logger.LogError("The userinfo request was rejected because the " +
                                        "'Authorization' header was invalid: {Header}.", header);

                        return(await SendUserinfoResponseAsync(new OpenIdConnectResponse
                        {
                            Error = OpenIdConnectConstants.Errors.InvalidRequest,
                            ErrorDescription = "The specified 'Authorization' header is invalid."
                        }));
                    }

                    token = header.Substring("Bearer ".Length);
                }
            }

            if (string.IsNullOrEmpty(token))
            {
                Logger.LogError("The userinfo request was rejected because the access token was missing.");

                return(await SendUserinfoResponseAsync(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidRequest,
                    ErrorDescription = "The mandatory 'access_token' parameter is missing."
                }));
            }

            var context = new ValidateUserinfoRequestContext(Context, Scheme, Options, request);
            await Provider.ValidateUserinfoRequest(context);

            if (context.Result != null)
            {
                if (context.Result.Handled)
                {
                    Logger.LogDebug("The userinfo request was handled in user code.");

                    return(true);
                }

                else if (context.Result.Skipped)
                {
                    Logger.LogDebug("The default userinfo request handling was skipped from user code.");

                    return(false);
                }
            }

            else if (context.IsRejected)
            {
                Logger.LogError("The userinfo request was rejected with the following error: {Error} ; {Description}",
                                /* Error: */ context.Error ?? OpenIdConnectConstants.Errors.InvalidRequest,
                                /* Description: */ context.ErrorDescription);

                return(await SendUserinfoResponseAsync(new OpenIdConnectResponse
                {
                    Error = context.Error ?? OpenIdConnectConstants.Errors.InvalidRequest,
                    ErrorDescription = context.ErrorDescription,
                    ErrorUri = context.ErrorUri
                }));
            }

            Logger.LogInformation("The userinfo request was successfully validated.");

            var ticket = await DeserializeAccessTokenAsync(token, request);

            if (ticket == null)
            {
                Logger.LogError("The userinfo request was rejected because the access token was invalid.");

                return(await SendUserinfoResponseAsync(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidToken,
                    ErrorDescription = "The specified access token is not valid."
                }));
            }

            if (ticket.Properties.ExpiresUtc.HasValue &&
                ticket.Properties.ExpiresUtc < Options.SystemClock.UtcNow)
            {
                Logger.LogError("The userinfo request was rejected because the access token was expired.");

                return(await SendUserinfoResponseAsync(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidToken,
                    ErrorDescription = "The specified access token is no longer valid."
                }));
            }

            var notification = new HandleUserinfoRequestContext(Context, Scheme, Options, request, ticket)
            {
                Issuer  = Context.GetIssuer(Options),
                Subject = ticket.Principal.GetClaim(OpenIdConnectConstants.Claims.Subject)
            };

            // Note: when receiving an access token, its audiences list cannot be used for the "aud" claim
            // as the client application is not the intented audience but only an authorized presenter.
            // See http://openid.net/specs/openid-connect-core-1_0.html#UserInfoResponse
            notification.Audiences.UnionWith(ticket.GetPresenters());

            // The following claims are all optional and should be excluded when
            // no corresponding value has been found in the authentication ticket.
            if (ticket.HasScope(OpenIdConnectConstants.Scopes.Profile))
            {
                notification.FamilyName = ticket.Principal.GetClaim(OpenIdConnectConstants.Claims.FamilyName);
                notification.GivenName  = ticket.Principal.GetClaim(OpenIdConnectConstants.Claims.GivenName);
                notification.BirthDate  = ticket.Principal.GetClaim(OpenIdConnectConstants.Claims.Birthdate);
            }

            if (ticket.HasScope(OpenIdConnectConstants.Scopes.Email))
            {
                notification.Email = ticket.Principal.GetClaim(OpenIdConnectConstants.Claims.Email);
            }

            if (ticket.HasScope(OpenIdConnectConstants.Scopes.Phone))
            {
                notification.PhoneNumber = ticket.Principal.GetClaim(OpenIdConnectConstants.Claims.PhoneNumber);
            }

            await Provider.HandleUserinfoRequest(notification);

            if (notification.Result != null)
            {
                if (notification.Result.Handled)
                {
                    Logger.LogDebug("The userinfo request was handled in user code.");

                    return(true);
                }

                else if (notification.Result.Skipped)
                {
                    Logger.LogDebug("The default userinfo request handling was skipped from user code.");

                    return(false);
                }
            }

            else if (notification.IsRejected)
            {
                Logger.LogError("The userinfo request was rejected with the following error: {Error} ; {Description}",
                                /* Error: */ notification.Error ?? OpenIdConnectConstants.Errors.InvalidRequest,
                                /* Description: */ notification.ErrorDescription);

                return(await SendUserinfoResponseAsync(new OpenIdConnectResponse
                {
                    Error = notification.Error ?? OpenIdConnectConstants.Errors.InvalidRequest,
                    ErrorDescription = notification.ErrorDescription,
                    ErrorUri = notification.ErrorUri
                }));
            }

            // Ensure the "sub" claim has been correctly populated.
            if (string.IsNullOrEmpty(notification.Subject))
            {
                throw new InvalidOperationException("The subject claim cannot be null or empty.");
            }

            var response = new OpenIdConnectResponse
            {
                [OpenIdConnectConstants.Claims.Subject]             = notification.Subject,
                [OpenIdConnectConstants.Claims.Address]             = notification.Address,
                [OpenIdConnectConstants.Claims.Birthdate]           = notification.BirthDate,
                [OpenIdConnectConstants.Claims.Email]               = notification.Email,
                [OpenIdConnectConstants.Claims.EmailVerified]       = notification.EmailVerified,
                [OpenIdConnectConstants.Claims.FamilyName]          = notification.FamilyName,
                [OpenIdConnectConstants.Claims.GivenName]           = notification.GivenName,
                [OpenIdConnectConstants.Claims.Issuer]              = notification.Issuer,
                [OpenIdConnectConstants.Claims.PhoneNumber]         = notification.PhoneNumber,
                [OpenIdConnectConstants.Claims.PhoneNumberVerified] = notification.PhoneNumberVerified,
                [OpenIdConnectConstants.Claims.PreferredUsername]   = notification.PreferredUsername,
                [OpenIdConnectConstants.Claims.Profile]             = notification.Profile,
                [OpenIdConnectConstants.Claims.Website]             = notification.Website
            };

            switch (notification.Audiences.Count)
            {
            case 0: break;

            case 1:
                response[OpenIdConnectConstants.Claims.Audience] = notification.Audiences.ElementAt(0);
                break;

            default:
                response[OpenIdConnectConstants.Claims.Audience] = new JArray(notification.Audiences);
                break;
            }

            foreach (var claim in notification.Claims)
            {
                response.SetParameter(claim.Key, claim.Value);
            }

            return(await SendUserinfoResponseAsync(response));
        }
            /// <summary>
            /// Called before the action executes, after model binding is complete
            /// </summary>
            /// <param name="context">A context for action filters</param>
            public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
            {
                await next();

                if (context == null || context.HttpContext == null || context.HttpContext.Request == null)
                {
                    return;
                }

                if (!DataSettingsHelper.DatabaseIsInstalled())
                {
                    return;
                }

                //only in GET requests
                if (!HttpMethods.IsGet(context.HttpContext.Request.Method))
                {
                    return;
                }

                //ajax request should not save
                bool isAjaxCall = context.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";

                if (isAjaxCall)
                {
                    return;
                }

                //whether is need to store last visited page URL
                if (!_customerSettings.StoreLastVisitedPage)
                {
                    return;
                }

                //get current page
                var pageUrl = _webHelper.GetThisPageUrl(true);

                if (string.IsNullOrEmpty(pageUrl))
                {
                    return;
                }

                //get previous last page
                var previousPageUrl = _workContext.CurrentCustomer.GetAttributeFromEntity <string>(SystemCustomerAttributeNames.LastVisitedPage);

                //save new one if don't match
                if (!pageUrl.Equals(previousPageUrl, StringComparison.OrdinalIgnoreCase))
                {
                    await _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.LastVisitedPage, pageUrl);
                }

                if (!string.IsNullOrEmpty(context.HttpContext.Request.Headers[HeaderNames.Referer]))
                {
                    if (!context.HttpContext.Request.Headers[HeaderNames.Referer].ToString().Contains(context.HttpContext.Request.Host.ToString()))
                    {
                        var previousUrlReferrer = _workContext.CurrentCustomer.GetAttribute <string>(_genericAttributeService, SystemCustomerAttributeNames.LastUrlReferrer);
                        var actualUrlReferrer   = context.HttpContext.Request.Headers[HeaderNames.Referer];
                        if (previousUrlReferrer != actualUrlReferrer)
                        {
                            await _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.LastUrlReferrer, actualUrlReferrer);
                        }
                    }
                }

                if (_customerSettings.SaveVisitedPage)
                {
                    if (!_workContext.CurrentCustomer.IsSearchEngineAccount())
                    {
                        await _customerActivityService.InsertActivityAsync("PublicStore.Url", pageUrl, pageUrl, _workContext.CurrentCustomer.Id, _webHelper.GetCurrentIpAddress());
                    }
                }
            }
Ejemplo n.º 51
0
 /// <summary>
 /// Make an HTTP Request to the Shopify API
 /// </summary>
 /// <param name="method">method to be used in the request</param>
 /// <param name="path">the path that should be requested</param>
 /// <seealso cref="http://api.shopify.com/"/>
 /// <returns>the server response</returns>
 public object Call(HttpMethods method, string path)
 {
     return Call(method, path, null);
 }
Ejemplo n.º 52
0
 public ControllerMethod(Type controllerType, HttpMethods method)
 {
     _controllerType = controllerType;
     _method = method;
 }
 public bool Equals(EdgeKey other)
 {
     return
         (IsCorsPreflightRequest == other.IsCorsPreflightRequest &&
          HttpMethods.Equals(HttpMethod, other.HttpMethod));
 }
 private static bool HasBody(string requestMethod)
 {
     return(HttpMethods.IsPut(requestMethod) || HttpMethods.IsPost(requestMethod));
 }
Ejemplo n.º 55
0
            public async void CallsOnNextWhenNewDataIsPersisted(HttpMethods method, string url, bool expectedResult)
            {
                var oldRequest = new HttpRequest(HttpMethods.Get, "http://localhost:3000/good");

                var sqlite = new Mock<ISQLiteAsyncConnection>();
                sqlite.Setup(s => s.Get<HttpRequest>()).Returns(Task.FromResult(new List<HttpRequest> { oldRequest }));

                var newRequest = new HttpRequest(method, url);
                var requestHistory = new RequestHistory(sqlite.Object);

                // if onnext is not called by the time the timeout happens, then call OnException.
                Observable.Timeout(requestHistory.GetRequestsObservable(), TimeSpan.FromSeconds(2))
                    .Subscribe(
                        _ => Assert.True(expectedResult),
                        ex => Assert.False(expectedResult));

                await requestHistory.AddRequestAsync(newRequest);
            }
Ejemplo n.º 56
0
 /// <summary>
 /// Make an HTTP Request to the Haravan API
 /// </summary>
 /// <param name="method">method to be used in the request</param>
 /// <param name="path">the path that should be requested</param>
 /// <seealso cref="http://api.haravan.com/"/>
 /// <returns>the server response</returns>
 public object Call(HttpMethods method, string path)
 {
     return(Call(method, path, null));
 }
Ejemplo n.º 57
0
 internal static bool IsGetOrHeadMethod(string method)
 {
     return(HttpMethods.IsGet(method) || HttpMethods.IsHead(method));
 }
Ejemplo n.º 58
0
        public RouteResolutionResult Apply(object request, string httpMethod)
        {
            if (!this.IsValid)
            {
                return(RouteResolutionResult.Error(this, this.ErrorMsg));
            }

            if (HttpMethods != null && HttpMethods.Length != 0 && httpMethod != null && !HttpMethods.Contains(httpMethod) && !HttpMethods.Contains("ANY"))
            {
                return(RouteResolutionResult.Error(this, "Allowed HTTP methods '{0}' does not support the specified '{1}' method."
                                                   .Fmt(HttpMethods.Join(", "), httpMethod)));
            }

            var uri = this.Path;

            var unmatchedVariables = new List <string>();

            foreach (var variable in this.variablesMap)
            {
                var property   = variable.Value;
                var value      = property.GetValue(request);
                var isWildCard = variable.Key.EndsWith("*");
                if (value == null && !isWildCard)
                {
                    unmatchedVariables.Add(variable.Key);
                    continue;
                }

                var variableValue = FormatVariable(value);
                uri = uri.Replace(VariablePrefix + variable.Key + VariablePostfix, variableValue);
            }

            if (unmatchedVariables.Any())
            {
                var errMsg = "Could not match following variables: " + string.Join(",", unmatchedVariables.ToArray());
                return(RouteResolutionResult.Error(this, errMsg));
            }

            return(RouteResolutionResult.Success(this, uri));
        }
Ejemplo n.º 59
0
        private void Download(string Url, HttpMethods Method = HttpMethods.GET, byte[] PostData = null, string Key = null, System.Net.CookieContainer CookieContainer = null, string Username = null, string Password = null, string Domain = null, string Accept = null, Boolean AllowAutoRedirect = false, string ContentType = null, bool UseDefaultCredentials = false, string UserAgent = null, WebHeaderCollection Headers = null)
        {
            try
            {
                Logger.Info(string.Format("Url:{0}, Method:{1}, Key:{2}, Username:{3}, Password:{4}, Domain:{5}, Accept:{6}, AllowAutoRedirect:{7}, ContentType:{8}, UseDefaultCredentials:{9}, UserAgent:{10}", Url, Method, Key, Username, Password, Domain, Accept, AllowAutoRedirect, ContentType, UseDefaultCredentials, UserAgent));
                StopWatch = new Stopwatch();
                StopWatch.Start();
                this.Key = Key;
                this.Url = Url;
                var request = (HttpWebRequest)WebRequest.Create(Url);

                if (Headers != null)
                {
                    foreach (var name in Headers.AllKeys)
                    {
                        try
                        {
                            request.Headers[name] = Headers[name];
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
                if (CookieContainer != null) request.CookieContainer = CookieContainer;
                this.ContentType = ContentType;
                this.Accept = Accept;
                this.AllowAutoRedirect = AllowAutoRedirect;
                this.UserAgent = UserAgent;

                request.AllowAutoRedirect = AllowAutoRedirect;
                if (CookieContainer != null) request.CookieContainer = CookieContainer;
                if (Accept != null) request.Accept = Accept;
                if (ContentType != null) request.ContentType = ContentType;
                if (UserAgent != null) request.UserAgent = UserAgent;

                if (!string.IsNullOrEmpty(Domain) && !string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password))
                {
                    request.Credentials = new System.Net.NetworkCredential(Username, Password, Domain);
                }
                else
                {
                    request.UseDefaultCredentials = UseDefaultCredentials;
                }
                request.Method = Method.ToString();

                if (Method == HttpMethods.POST || Method == HttpMethods.OPTIONS)
                {
                    _PostData = PostData;
                    //for post, we typically are posting data, lets get the request stream
                    request.ContentType = "application/x-www-form-urlencoded";
                    //request.BeginGetRequestStream(BeginRequest, request);
                    request.BeginGetRequestStream(new AsyncCallback(BeginRequest), request);
                    HasElapsed();
                }
                else
                {
                    //for get's we just jump directly to the get respnose
                    request.BeginGetResponse(new AsyncCallback(HandleResponse), request);
                    HasElapsed();
                }

            }
            catch (Exception e)
            {
                if (OnHttpDownloadError != null) OnHttpDownloadError(this, e, this.Key);
            }
        }
Ejemplo n.º 60
0
        private async Task HandleHttpRequest(HttpContext context)
        {
            var requestMessage = new HttpRequestMessage();
            var requestMethod  = context.Request.Method;

            if (!HttpMethods.IsGet(requestMethod) &&
                !HttpMethods.IsHead(requestMethod) &&
                !HttpMethods.IsDelete(requestMethod) &&
                !HttpMethods.IsTrace(requestMethod))
            {
                var streamContent = new StreamContent(context.Request.Body);
                requestMessage.Content = streamContent;
            }

            // Copy the request headers
            foreach (var header in context.Request.Headers)
            {
                if (header.Key.Equals("Referer") || header.Key.Equals("Origin"))
                {
                    requestMessage.Headers.TryAddWithoutValidation(header.Key, new string[] { header.Value[0].Replace("https://localhost:8081", "https://www.habbo.com") });
                }
                else
                {
                    if (!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()) && requestMessage.Content != null)
                    {
                        requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
                    }
                }
            }

            requestMessage.Headers.Host = _options.Host + ":" + _options.Port;
            string path;

            if (_options.Strip)
            {
                path = context.Request.Path.Value.Replace(_options.StripPath, "");
            }
            else
            {
                path = context.Request.Path;
            }

            var uriString = $"{_options.Scheme}://{_options.Host}:{_options.Port}{context.Request.PathBase}{path}{context.Request.QueryString}";

            requestMessage.RequestUri = new Uri(uriString);
            requestMessage.Method     = new HttpMethod(context.Request.Method);
            using (var responseMessage = await _httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
            {
                responseMessage.Content = await ReplaceContent(responseMessage, path);

                context.Response.StatusCode = (int)responseMessage.StatusCode;

                foreach (var header in responseMessage.Headers)
                {
                    context.Response.Headers[header.Key] = header.Value.ToArray();
                }

                foreach (var header in responseMessage.Content.Headers)
                {
                    context.Response.Headers[header.Key] = header.Value.ToArray();
                }

                // SendAsync removes chunking from the response. This removes the header so it doesn't expect a chunked response.
                context.Response.Headers.Remove("transfer-encoding");
                if (!context.Response.StatusCode.Equals(StatusCodes.Status204NoContent))
                {
                    await responseMessage.Content.CopyToAsync(context.Response.Body);
                }
            }
        }