private static async Task<IValueProvider> CreateValueProviderAsync(HttpRequest request)
 {
     return new FormValueProvider(
         BindingSource.Form,
         await request.ReadFormAsync(),
         CultureInfo.CurrentCulture);
 }
        private static bool TryGetApiKey(HttpRequest request, out string apiKey)
        {
            StringValues headerValue;
            if (request.Headers.TryGetValue("Authorization", out headerValue))
            {
                AuthenticationHeaderValue authHeaderValue;
                if (AuthenticationHeaderValue.TryParse(headerValue, out authHeaderValue))
                {
                    apiKey = authHeaderValue.Parameter;
                    return true;
                }
            }

            if (request.Headers.TryGetValue("X-Octopus-ApiKey", out headerValue))
            {
                apiKey = headerValue;
                return true;
            }

            if (request.Headers.TryGetValue("X-NuGet-ApiKey", out headerValue))
            {
                apiKey = headerValue;
                return true;
            }

            if (request.Query.ContainsKey("apikey"))
            {
                apiKey = request.Query["apikey"];
                return true;
            }

            apiKey = null;
            return false;
        }
        private static bool ParseAuthenticationHeader(MgHttpRequestParam param, HttpRequest request)
        {
            //This method decodes and extracts the username and password from the http authentication
            //header (if it exists) and packs the values into the MgHttpRequestParam object if they
            //exist
            String auth = request.Headers["authorization"];
            if (auth != null && auth.Length > 6)
            {
                auth = auth.Substring(6);
                byte[] decoded = Convert.FromBase64String(auth);
                String decodedStr = Encoding.UTF8.GetString(decoded);
                String[] decodedTokens = decodedStr.Split(':');
                if (decodedTokens.Length == 1 || decodedTokens.Length == 2)
                {
                    String username = decodedTokens[0];
                    String password = "";
                    if (decodedTokens.Length == 2)
                        password = decodedTokens[1];

                    param.AddParameter("USERNAME", username);
                    param.AddParameter("PASSWORD", password);
                    return true;
                }
            }
            return false;
        }
        public StaticFileContext(HttpContext context, StaticFileOptions options, PathString matchUrl, ILogger logger)
        {
            _context = context;
            _options = options;
            _matchUrl = matchUrl;
            _request = context.Request;
            _response = context.Response;
            _logger = logger;
            _requestHeaders = _request.GetTypedHeaders();
            _responseHeaders = _response.GetTypedHeaders();

            _method = null;
            _isGet = false;
            _isHead = false;
            _subPath = PathString.Empty;
            _contentType = null;
            _fileInfo = null;
            _length = 0;
            _lastModified = new DateTimeOffset();
            _etag = null;
            _ifMatchState = PreconditionState.Unspecified;
            _ifNoneMatchState = PreconditionState.Unspecified;
            _ifModifiedSinceState = PreconditionState.Unspecified;
            _ifUnmodifiedSinceState = PreconditionState.Unspecified;
            _ranges = null;
        }
Example #5
0
        public static string Combine(HttpRequest request, string path, params Descriptor[] descriptors)
        {
            StringBuilder result = new StringBuilder();

              foreach (Descriptor descriptor in descriptors)
              {
            if (!descriptor.Skip)
            {
              string value = descriptor.TakeFromUrl ? request.Query[descriptor.Name] : descriptor.Value;

              if (!string.IsNullOrEmpty(value))
            result.AppendFormat("{0}{1}={2}", result.Length == 0 ? '?' : '&', descriptor.Name, value);
            }
              }

              foreach (KeyValuePair<string, string[]> keyValuePair in request.Query)
              {
            if (!descriptors.Any(d => d.Name == keyValuePair.Key))
            {
              string value = request.Query[keyValuePair.Key];

              if (!string.IsNullOrEmpty(value))
            result.AppendFormat("{0}{1}={2}", result.Length == 0 ? '?' : '&', keyValuePair.Key, value);
            }
              }

              result.Insert(0, string.IsNullOrEmpty(path) ? request.Path.ToString() : path);
              return result.ToString();
        }
 private static async Task<IValueProvider> CreateValueProviderAsync(HttpRequest request)
 {
     return new JQueryFormValueProvider(
             BindingSource.Form,
             await GetValueCollectionAsync(request),
             CultureInfo.CurrentCulture);
 }
        /*
         *  Very simple logger that logs to the VS Debug output window. Requires the debugger to be attached to work!
         */

        public void Log(HttpRequest request, Exception ex)
        {
            /*
             *  Simplification due to time restrictions.
             */
            Log(ex);
        }
        protected override async Task OnReceived(HttpRequest request, string connectionId, string data) {
            var identity = request.HttpContext.User.Identity;
            var status = identity.IsAuthenticated ? "authenticated" : "unauthenticated";
            var name = identity.IsAuthenticated ? identity.Name : "client";

            await Connection.Send(connectionId, $"Received an {status} message from {name}: {data}");
        }
Example #9
0
        private bool RequestingSwaggerUi(HttpRequest request)
        {
            if (request.Method != "GET") return false;

            var routeValues = _requestMatcher.Match(request.Path.ToUriComponent().Trim('/'));
            return (routeValues != null);
        }
Example #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ODataQueryOptions"/> class based on the incoming request and some metadata information from
        /// the <see cref="ODataQueryContext"/>.
        /// </summary>
        /// <param name="context">The <see cref="ODataQueryContext"/> which contains the <see cref="IEdmModel"/> and some type information.</param>
        /// <param name="request">The incoming request message.</param>
        public ODataQueryOptions(ODataQueryContext context, HttpRequest request)
        {
            if (context == null)
            {
                throw Error.ArgumentNull("context");
            }

            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            _assemblyProvider = request.AssemblyProvider();

            Context = context;
            Request = request;
            RawValues = new ODataRawQueryOptions();

            var queryOptionDict = request.Query.ToDictionary(p => p.Key, p => p.Value.FirstOrDefault());
            _queryOptionParser = new ODataQueryOptionParser(
                context.Model,
                context.ElementType,
                context.NavigationSource,
                queryOptionDict);
            
            BuildQueryOptions(queryOptionDict);
        }
Example #11
0
        public virtual object ApplyQueryOptions(object value, HttpRequest request, ActionDescriptor descriptor)
        {
            var elementClrType = TypeHelper.GetImplementedIEnumerableType(value.GetType());

            var model = request.ODataProperties().Model;
            if (model == null)
            {
                throw Error.InvalidOperation(SRResources.QueryGetModelMustNotReturnNull);
            }

            var queryContext = new ODataQueryContext(
                model,
                elementClrType,
                request.ODataProperties().Path);

            var queryOptions = new ODataQueryOptions(queryContext, request);

            var enumerable = value as IEnumerable;
            if (enumerable == null)
            {
                // response is single entity.
                return value;
            }

            // response is a collection.
            var query = (value as IQueryable) ?? enumerable.AsQueryable();
            return queryOptions.ApplyTo(query,
                new ODataQuerySettings
                {
                    HandleNullPropagation = HandleNullPropagationOption.True
                });
        }
Example #12
0
        private bool RequestingSwaggerUi(HttpRequest request)
        {
            if (request.Method != "GET") return false;

            var routeValues = _requestMatcher.Match(request.Path);
            return (routeValues != null);
        }
Example #13
0
		public BasicAuthIdentity GetBasicAuth(HttpRequest request)
		{
			BasicAuthIdentity identity = null;
			var headerValue = request.Headers["Authorization"];
			if (!String.IsNullOrEmpty(headerValue))
			{
				var headerValues = headerValue.Split(' ');
				var scheme = headerValues[0];
				if (string.Compare(scheme, "Basic", true) == 0)
				{
					var encodedUsernameAndPassword = headerValues[1];
					
					var usernameAndPassword = Encoding.UTF8.GetString(Convert.FromBase64String(encodedUsernameAndPassword));
					if (usernameAndPassword != null && usernameAndPassword != ":")
					{
						var tokens = usernameAndPassword.Split(':');
						switch (tokens.Length)
						{
							case 2:
								identity = new BasicAuthIdentity(tokens[0], tokens[1]);
								break;
							case 1:
								identity = new BasicAuthIdentity(tokens[0], null);
								break;
							default:
								identity = null;
								break;
						}
					}
				}
			}

			return identity;
		}
Example #14
0
        protected override Task OnDisconnected(HttpRequest request, string connectionId, bool stopCalled)
        {
            string ignored;
            _users.TryRemove(connectionId, out ignored);

            string suffix = stopCalled ? "cleanly" : "uncleanly";
            return Connection.Broadcast(DateTime.Now + ": " + GetUser(connectionId) + " disconnected " + suffix);
        }
Example #15
0
 internal static bool RequestPrefersReturnNoContent(HttpRequest request)
 {
     string[] preferences = null;
     if (request.Headers.TryGetValue(PreferHeaderName, out preferences))
     {
         return preferences.Contains(ReturnNoContentHeaderValue);
     }
     return false;
 }
Example #16
0
 public OrderedFileSet(IEnumerable<IWebFile> files,            
     FileSystemHelper fileSystemHelper, 
     HttpRequest request,
     PreProcessPipeline defaultPipeline)
 {
     _files = files;
     _defaultPipeline = defaultPipeline;
     _fileSystemHelper = fileSystemHelper;
     _request = request;
 }
        /// <summary>
        /// Get a redirect uri using standard options
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private static string GetStandardRedirectUri(HttpRequest request)
        {
            var uri = new UriBuilder();
            uri.Scheme = "https";
            uri.Host = RemovePort.Replace(request.Host.Value, String.Empty);
            uri.Path = request.Path.Value;
            uri.Query = request.QueryString.Value;

            return uri.ToString();
        }
        private IStreamDiscovery CreateStreamDiscovery(HttpRequest request)
        {
            var streams = request.Query["streams"];
            if( streams.FirstOrDefault() != null)
            {
                return new StaticStreamDiscovery(streams.Select(uri=>uri.Trim()));
            }

            var cluster = request.Query["cluster"].FirstOrDefault();
            return new EtcdStreamDiscovery(cluster);
        }
        public static string GetHeaderInformation(HttpRequest request)
        {
          var sb = new StringBuilder();

          IHeaderDictionary headers = request.Headers;
          foreach (var header in request.Headers)
          {
            sb.Append(GetDiv(header.Key, string.Join("; ", header.Value)));
          }
          return sb.ToString();
        }
        public static IObservable<IDictionary<string, object>> ReceiveSse(string address, HttpRequest origin, CancellationTokenSource token, IObservable<StreamAction> streamRemoved)
        {
            return Observable.Create<IDictionary<string, object>>((Func<IObserver<IDictionary<string, object>>, Task>)(async (IObserver<IDictionary<string, object>> observer) =>
            {
                var subscription = streamRemoved.Where(a => a.Uri == address).Subscribe(o => {
                    token.Cancel();
                });

                var client = new HttpClient();
                var builder = new UriBuilder(address);
                if(!String.IsNullOrWhiteSpace( origin.QueryString.Value))
                    builder.Query = origin.QueryString.Value.Substring(1);
                var uri = builder.Uri;

                await Task.Delay(TimeSpan.FromSeconds(1));

                while (true)
                {
                    try
                    {
                        //Console.WriteLine("Get info for " + address);

                        using (var response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, token.Token).ConfigureAwait(false))
                        {
                            response.EnsureSuccessStatusCode();

                            var stream = new StreamReader(await response.Content.ReadAsStreamAsync());
                            while (!token.IsCancellationRequested)
                            {
                                var line = await stream.ReadLineAsync();
                                if (line.Length > 0 && line.StartsWith("data: "))
                                {
                                    var data = DeserializeData(line.Substring("data: ".Length));
                                    data["instanceId"] =  uri.Authority.ToString();
                                    //Console.WriteLine($"{uri.Authority} -> {data["requestCount"]}");
                                    observer.OnNext(data);
                                }

                                await Task.Yield();
                            }
                        }
                    }
                    catch(Exception ex)
                    {
                        if (IsSocketException(ex) || token.IsCancellationRequested) break;
                        //Console.WriteLine("Error waiting 10 sec for " + address);
                        await Task.Delay(TimeSpan.FromSeconds(10));
                    }
                }

                //Console.WriteLine("Completed for " + address);
                observer.OnCompleted();
            }));
        }
        private bool RequestingSwaggerDocs(HttpRequest request, out string apiVersion)
        {
            apiVersion = null;
            if (request.Method != "GET") return false;

            var routeValues = _requestMatcher.Match(request.Path.ToUriComponent().Trim('/'));
            if (routeValues == null || !routeValues.ContainsKey("apiVersion")) return false;

            apiVersion = routeValues["apiVersion"].ToString();
            return true;
        }
Example #22
0
        internal static string GetRequestPreferHeader(HttpRequest request)
        {
            string[] values;
            if (request.Headers.TryGetValue(PreferHeaderName, out values))
            {
                // If there are many "Prefer" headers, pick up the first one.
                return values.FirstOrDefault();
            }

            return null;
        }
        protected override async Task OnConnected(HttpRequest request, string connectionId) {
            var identity = request.HttpContext.User.Identity;
            var status = identity.IsAuthenticated ? "Authenticated" : "Unauthenticated";

            Logger.LogInformation($"{status} connection {connectionId} has just connected.");

            await Connection.Send(connectionId, $"Connection is {status}");

            if (identity.IsAuthenticated) {
                await Connection.Send(connectionId, $"Authenticated username: {identity.Name}");
            }
        }
        private static async Task<IDictionary<string, StringValues>> GetValueCollectionAsync(HttpRequest request)
        {
            var formCollection = await request.ReadFormAsync();

            var dictionary = new Dictionary<string, StringValues>(StringComparer.OrdinalIgnoreCase);
            foreach (var entry in formCollection)
            {
                var key = NormalizeJQueryToMvc(entry.Key);
                dictionary[key] = entry.Value;
            }

            return dictionary;
        }
        /// <summary>
        /// Creates a new instance of the <see cref="HttpClient"/> class.
        /// </summary>
        /// <param name="request"><see cref="HttpRequest"/> instance.</param>
        /// <param name="handler"><see cref="HttpMessageHandler"/> instance.</param>
        /// <returns>Returns the <see cref="HttpClient"/> instance created.</returns>
        public HttpClient CreateHttpClient(HttpRequest request, HttpMessageHandler handler = null)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var url = string.Join("://", request.IsHttps ? "https" : "http", request.Host.Value);
            var baseAddressUri = new Uri(url);

            var client = handler == null ? new HttpClient() : new HttpClient(handler, true);
            client.BaseAddress = baseAddressUri;
            return client;
        }
Example #26
0
        /// <summary>
        /// Creates a SharePointContext instance with the specified HTTP request.
        /// </summary>
        /// <param name="httpRequest">The HTTP request.</param>
        /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
        public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
        {
            if (httpRequest == null)
            {
                throw new ArgumentNullException(nameof(httpRequest));
            }

            // SPHostUrl
            Uri spHostUrl = SharePointContext.GetUriFromQueryStringParameter(httpRequest, SharePointContext.SPHostUrlKey);

            if (spHostUrl == null)
            {
                return(null);
            }

            // SPAppWebUrl
            Uri spAppWebUrl = SharePointContext.GetUriFromQueryStringParameter(httpRequest, SharePointContext.SPAppWebUrlKey);

            if (spAppWebUrl == null)
            {
                spAppWebUrl = null;
            }

            // SPLanguage
            string spLanguage = httpRequest.Query[SharePointContext.SPLanguageKey];

            if (string.IsNullOrEmpty(spLanguage))
            {
                return(null);
            }

            // SPClientTag
            string spClientTag = httpRequest.Query[SharePointContext.SPClientTagKey];

            if (string.IsNullOrEmpty(spClientTag))
            {
                return(null);
            }

            // SPProductNumber
            string spProductNumber = httpRequest.Query[SharePointContext.SPProductNumberKey];

            if (string.IsNullOrEmpty(spProductNumber))
            {
                return(null);
            }

            return(CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest));
        }
        /// <summary>
        /// Determines whether client is authorized to connect to <see cref="IHub"/>.
        /// </summary>
        /// <param name="hubDescriptor">Description of the hub client is attempting to connect to.</param>
        /// <param name="request">The (re)connect request from the client.</param>
        /// <returns>true if the caller is authorized to connect to the hub; otherwise, false.</returns>
        public virtual bool AuthorizeHubConnection(HubDescriptor hubDescriptor, HttpRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            // If RequireOutgoing is explicitly set to false, authorize all connections.
            if (_requireOutgoing.HasValue && !_requireOutgoing.Value)
            {
                return true;
            }

            return UserAuthorized(request.HttpContext.User);
        }
        /// <summary>
        /// Gets the SharePoint host url from QueryString of the specified HTTP request.
        /// </summary>
        /// <param name="httpRequest">The specified HTTP request.</param>
        /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
        public static Uri GetUriFromQueryStringParameter(HttpRequest httpRequest, string queryStringParameter)
        {
            if (httpRequest == null) { throw new ArgumentNullException(nameof(httpRequest)); }

            string parameterValue = TokenHandler.EnsureTrailingSlash(httpRequest.Query[queryStringParameter]);
            Uri uriValue;

            if (Uri.TryCreate(parameterValue, UriKind.Absolute, out uriValue) &&
               (uriValue.Scheme == Uri.UriSchemeHttp || uriValue.Scheme == Uri.UriSchemeHttps))
            {
                return uriValue;
            }

            return null;
        }
        public static string GetRequestInformation(HttpRequest request)
        {
          var sb = new StringBuilder();
          sb.Append(GetDiv("scheme", request.Scheme));
          sb.Append(GetDiv("host", request.Host.HasValue ? request.Host.Value : 
            "no host"));
          sb.Append(GetDiv("path", request.Path));
          sb.Append(GetDiv("query string", request.QueryString.HasValue ? 
            request.QueryString.Value : "no query string"));

          sb.Append(GetDiv("method", request.Method));
          sb.Append(GetDiv("protocol", request.Protocol));

          return sb.ToString();
        }
        public string GetUserId(HttpRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            var user = request.HttpContext.User;
            if (user != null && user.Identity != null)
            {
                return user.Identity.Name;
            }

            return null;
        }
Example #31
0
        /// <summary>
        /// Returns the ordered collection of files for the bundle
        /// </summary>
        /// <param name="bundleName"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        public IEnumerable<IWebFile> GetFiles(string bundleName, HttpRequest request)
        {
            BundleFileCollection collection;
            if (!_bundles.TryGetValue(bundleName, out collection)) return null;

            //the file type in the bundle will always be the same
            var first = collection.Files.FirstOrDefault();
            if (first == null) return Enumerable.Empty<IWebFile>();

            var orderedSet = new OrderedFileSet(collection.Files, _fileSystemHelper, request,
                _processorFactory.GetDefault(first.DependencyType));
            var ordered = orderedSet.GetOrderedFileSet();

            //call the registered callback if any is set
            return collection.OrderingCallback == null ? ordered : collection.OrderingCallback(ordered);
        }
Example #32
0
        /// <summary>
        /// Gets the SharePoint host url from QueryString of the specified HTTP request.
        /// </summary>
        /// <param name="httpRequest">The specified HTTP request.</param>
        /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
        public static Uri GetUriFromQueryStringParameter(HttpRequest httpRequest, string queryStringParameter)
        {
            if (httpRequest == null)
            {
                throw new ArgumentNullException(nameof(httpRequest));
            }

            string parameterValue = TokenHandler.EnsureTrailingSlash(httpRequest.Query[queryStringParameter]);
            Uri    uriValue;

            if (Uri.TryCreate(parameterValue, UriKind.Absolute, out uriValue) &&
                (uriValue.Scheme == Uri.UriSchemeHttp || uriValue.Scheme == Uri.UriSchemeHttps))
            {
                return(uriValue);
            }

            return(null);
        }
Example #33
0
 public HttpRequest(Microsoft.AspNet.Http.HttpRequest request, Microsoft.AspNet.Http.Features.IHttpConnectionFeature connectionFeature)
 {
     _request           = request;
     _connectionFeature = connectionFeature;
 }
Example #34
0
        protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequest httpRequest)
        {
            string contextTokenString = TokenHandler.GetContextTokenFromRequest(httpRequest);

            if (string.IsNullOrEmpty(contextTokenString))
            {
                return(null);
            }

            SharePointContextToken contextToken = null;

            try
            {
                contextToken = TokenHandler.ReadAndValidateContextToken(contextTokenString, httpRequest.Host.Value);
            }
            catch (WebException)
            {
                return(null);
            }
            catch (AudienceUriValidationFailedException)
            {
                return(null);
            }

            return(new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken, Configuration));
        }
Example #35
0
 public Uploader(IHostingEnvironment _env, Microsoft.AspNet.Http.HttpRequest request)
 {
     this._env     = _env;
     this._request = request;
 }
Example #36
0
 /// <summary>
 /// Creates a SharePointContext instance.
 /// </summary>
 /// <param name="spHostUrl">The SharePoint host url.</param>
 /// <param name="spAppWebUrl">The SharePoint app web url.</param>
 /// <param name="spLanguage">The SharePoint language.</param>
 /// <param name="spClientTag">The SharePoint client tag.</param>
 /// <param name="spProductNumber">The SharePoint product number.</param>
 /// <param name="httpRequest">The HTTP request.</param>
 /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
 protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequest httpRequest);