private void ConfigureAuthorizerHttpClient(IServiceCollection services,
                                                   HttpClient client,
                                                   AuthorizerSetting settings,
                                                   CorsSetting corsSettings)
        {
            // access the DI container
            var serviceProvider = services.BuildServiceProvider();

            // Find the HttpContextAccessor service
            var httpContextAccessor = serviceProvider.GetService <IHttpContextAccessor>();

            // Get the bearer token from the request context (header)
            string bearerToken = null;

            bearerToken = httpContextAccessor.HttpContext.Request
                          .Headers["Authorization"]
                          .FirstOrDefault(h => h.StartsWith("bearer ", StringComparison.InvariantCultureIgnoreCase));

            // Add authorization if found
            if (bearerToken != null)
            {
                client.DefaultRequestHeaders.Add("Authorization", bearerToken);
            }

            // Add origin header
            if (corsSettings != null && corsSettings.AllowedOrigins.Length > 0)
            {
                client.DefaultRequestHeaders.Add("Origin", $"{httpContextAccessor.HttpContext.Request.Scheme}://{httpContextAccessor.HttpContext.Request.Host.Value}");
            }

            //Other Settings
            client.BaseAddress = new Uri($"{settings.Authority}/");
            client.DefaultRequestHeaders.Add("Accept", "application/x-www-form-urlencoded");
        }
        public void InstallServices(IServiceCollection services, IConfiguration configuration)
        {
            var authorizerSetting = new AuthorizerSetting();

            configuration.GetSection("Authorizer").Bind(authorizerSetting);

            if (!services.Any(x => x.ServiceType == typeof(AuthorizerSetting)))
            {
                services.AddSingleton(authorizerSetting);
            }

            var corsSetting = new CorsSetting();

            configuration.GetSection(nameof(CorsSetting)).Bind(corsSetting);

            if (!services.Any(x => x.ServiceType == typeof(CorsSetting)))
            {
                services.AddSingleton(corsSetting);
            }

            // http client services
            services.AddHttpClient("authorizer", c =>
            {
                ConfigureAuthorizerHttpClient(services, c, authorizerSetting, corsSetting);
            });
        }
        public void InstallServices(IServiceCollection services, IConfiguration configuration)
        {
            var corsSetting = new CorsSetting();

            configuration.GetSection(nameof(CorsSetting)).Bind(corsSetting);

            if (!services.Any(x => x.ServiceType == typeof(CorsSetting)))
            {
                services.AddSingleton(corsSetting);
            }

            services.AddCors(options =>
            {
                options.AddDefaultPolicy(
                    builder =>
                {
                    builder.WithOrigins(corsSetting.AllowedOrigins)
                    .AllowAnyMethod()
                    .AllowAnyHeader();
                });
            });
        }
Exemplo n.º 4
0
 /// <summary>
 /// Performs a potentially CORS-enabled fetch from the given URI by using an asynchronous GET request.
 /// </summary>
 /// <param name="requester">The requester to use.</param>
 /// <param name="url">The url that yields the path to the desired action.</param>
 /// <param name="cors">The cross origin settings to use.</param>
 /// <param name="origin">The origin of the page that requests the loading.</param>
 /// <param name="defaultBehavior">The default behavior in case it is undefined.</param>
 /// <param name="cancel">The token which can be used to cancel the request.</param>
 /// <returns>The task which will eventually return the stream.</returns>
 public static Task <IResponse> LoadWithCorsAsync(this IRequester requester, Url url, CorsSetting cors, String origin, OriginBehavior defaultBehavior, CancellationToken cancel)
 {
     //TODO
     //http://www.w3.org/TR/html5/infrastructure.html#potentially-cors-enabled-fetch
     return(requester.RequestAsync(new DefaultRequest
     {
         Address = url,
         Method = HttpMethod.Get
     }, cancel));
 }
Exemplo n.º 5
0
 /// <summary>
 /// Performs a potentially CORS-enabled fetch from the given URI by using an asynchronous GET request.
 /// </summary>
 /// <param name="requester">The requester to use.</param>
 /// <param name="url">The url that yields the path to the desired action.</param>
 /// <param name="cors">The cross origin settings to use.</param>
 /// <param name="origin">The origin of the page that requests the loading.</param>
 /// <param name="defaultBehavior">The default behavior in case it is undefined.</param>
 /// <returns>The task which will eventually return the stream.</returns>
 public static Task <IResponse> LoadWithCorsAsync(this IRequester requester, Url url, CorsSetting cors, String origin, OriginBehavior defaultBehavior)
 {
     return(requester.LoadWithCorsAsync(url, cors, origin, defaultBehavior, CancellationToken.None));
 }
Exemplo n.º 6
0
        /// <summary>
        /// Performs a potentially CORS-enabled fetch from the given URI by
        /// using an asynchronous GET request. For more information see:
        /// http://www.w3.org/TR/html5/infrastructure.html#potentially-cors-enabled-fetch
        /// </summary>
        /// <param name="loader">The resource loader to use.</param>
        /// <param name="request">The request to issue.</param>
        /// <param name="setting">The cross origin settings to use.</param>
        /// <param name="behavior">
        /// The default behavior in case it is undefined.
        /// </param>
        /// <param name="cancel">
        /// The token which can be used to cancel the request.
        /// </param>
        /// <returns>
        /// The task which will eventually return the stream.
        /// </returns>
        public static async Task<IResponse> FetchWithCorsAsync(this IResourceLoader loader, ResourceRequest request, CorsSetting setting, OriginBehavior behavior, CancellationToken cancel)
        {
            if (loader == null)
                return null;

            var url = request.Target;

            if (request.Origin == url.Origin || url.Scheme == KnownProtocols.Data || url.Href == "about:blank")
            {
                while (true)
                {
                    var data = new ResourceRequest(request.Source, url)
                    {
                        Origin = request.Origin,
                        IsManualRedirectDesired = true
                    };

                    var result = await loader.LoadAsync(data, cancel).ConfigureAwait(false);

                    if (result.StatusCode == HttpStatusCode.Redirect ||
                        result.StatusCode == HttpStatusCode.RedirectKeepVerb ||
                        result.StatusCode == HttpStatusCode.RedirectMethod ||
                        result.StatusCode == HttpStatusCode.TemporaryRedirect ||
                        result.StatusCode == HttpStatusCode.MovedPermanently ||
                        result.StatusCode == HttpStatusCode.MultipleChoices)
                    {
                        url = new Url(result.Headers.GetOrDefault(HeaderNames.Location, url.Href));

                        if (request.Origin == url.Origin)
                        {
                            request = new ResourceRequest(request.Source, url)
                            {
                                IsCookieBlocked = request.IsCookieBlocked,
                                IsSameOriginForced = request.IsSameOriginForced,
                                Origin = request.Origin
                            };
                            return await loader.FetchWithCorsAsync(request, setting, behavior, cancel).ConfigureAwait(false);
                        }
                    }
                    else
                    {
                        return result;
                    }
                }
            }

            if (setting == CorsSetting.None)
            {
                if (behavior == OriginBehavior.Taint)
                    await loader.LoadAsync(request, cancel).ConfigureAwait(false);
            }

            if (setting == CorsSetting.Anonymous)
                request.IsCredentialOmitted = true;

            if (setting == CorsSetting.Anonymous || setting == CorsSetting.UseCredentials)
            {
                var result = await loader.FetchAsync(request, cancel).ConfigureAwait(false);

                //TODO If CORS cross-origin request is success
                if (result != null && result.StatusCode == HttpStatusCode.OK)
                    return result;
            }

            throw new DomException(DomError.Network);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Performs a potentially CORS-enabled fetch from the given URI by
        /// using an asynchronous GET request. For more information see:
        /// http://www.w3.org/TR/html5/infrastructure.html#potentially-cors-enabled-fetch
        /// </summary>
        /// <param name="loader">The resource loader to use.</param>
        /// <param name="request">The request to issue.</param>
        /// <param name="setting">The cross origin settings to use.</param>
        /// <param name="behavior">
        /// The default behavior in case it is undefined.
        /// </param>
        /// <param name="cancel">
        /// The token which can be used to cancel the request.
        /// </param>
        /// <returns>
        /// The task which will eventually return the stream.
        /// </returns>
        public static async Task <IResponse> FetchWithCorsAsync(this IResourceLoader loader, ResourceRequest request, CorsSetting setting, OriginBehavior behavior, CancellationToken cancel)
        {
            if (loader == null)
            {
                return(null);
            }

            var url = request.Target;

            if (request.Origin == url.Origin || url.Scheme == KnownProtocols.Data || url.Href == "about:blank")
            {
                while (true)
                {
                    var data = new ResourceRequest(request.Source, url)
                    {
                        Origin = request.Origin,
                        IsManualRedirectDesired = true
                    };

                    var result = await loader.LoadAsync(data, cancel).ConfigureAwait(false);

                    if (result.StatusCode == HttpStatusCode.Redirect ||
                        result.StatusCode == HttpStatusCode.RedirectKeepVerb ||
                        result.StatusCode == HttpStatusCode.RedirectMethod ||
                        result.StatusCode == HttpStatusCode.TemporaryRedirect ||
                        result.StatusCode == HttpStatusCode.MovedPermanently ||
                        result.StatusCode == HttpStatusCode.MultipleChoices)
                    {
                        url = new Url(result.Headers.GetOrDefault(HeaderNames.Location, url.Href));

                        if (request.Origin == url.Origin)
                        {
                            request = new ResourceRequest(request.Source, url)
                            {
                                IsCookieBlocked    = request.IsCookieBlocked,
                                IsSameOriginForced = request.IsSameOriginForced,
                                Origin             = request.Origin
                            };
                            return(await loader.FetchWithCorsAsync(request, setting, behavior, cancel).ConfigureAwait(false));
                        }
                    }
                    else
                    {
                        return(result);
                    }
                }
            }
            else if (setting == CorsSetting.None)
            {
                if (behavior == OriginBehavior.Fail)
                {
                    throw new DomException(DomError.Network);
                }

                return(await loader.LoadAsync(request, cancel).ConfigureAwait(false));
            }
            else if (setting == CorsSetting.Anonymous || setting == CorsSetting.UseCredentials)
            {
                request.IsCredentialOmitted = setting == CorsSetting.Anonymous;
                var result = await loader.FetchAsync(request, cancel).ConfigureAwait(false);

                if (result != null && result.StatusCode == HttpStatusCode.OK)
                {
                    return(result);
                }
                else if (result != null)
                {
                    result.Dispose();
                }
            }

            throw new DomException(DomError.Network);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Performs a potentially CORS-enabled fetch from the given URI by
        /// using an asynchronous GET request. For more information see:
        /// http://www.w3.org/TR/html5/infrastructure.html#potentially-cors-enabled-fetch
        /// </summary>
        /// <param name="loader">The resource loader to use.</param>
        /// <param name="request">The request to issue.</param>
        /// <param name="setting">The cross origin settings to use.</param>
        /// <param name="behavior">
        /// The default behavior in case it is undefined.
        /// </param>
        /// <returns>
        /// The task which will eventually return the stream.
        /// </returns>
        public static async Task <IResponse> FetchWithCorsAsync(this IResourceLoader loader, ResourceRequest request, CorsSetting setting, OriginBehavior behavior)
        {
            var url = request.Target;

            if (request.Origin == url.Origin || url.Scheme == ProtocolNames.Data || url.Href == "about:blank")
            {
                while (true)
                {
                    var data = new ResourceRequest(request.Source, url)
                    {
                        Origin = request.Origin,
                        IsManualRedirectDesired = true
                    };

                    var result = await loader.DownloadAsync(data).Task.ConfigureAwait(false);

                    if (result.IsRedirected())
                    {
                        url = new Url(result.Headers.GetOrDefault(HeaderNames.Location, url.Href));

                        if (request.Origin.Is(url.Origin))
                        {
                            request = new ResourceRequest(request.Source, url)
                            {
                                IsCookieBlocked    = request.IsCookieBlocked,
                                IsSameOriginForced = request.IsSameOriginForced,
                                Origin             = request.Origin
                            };
                            return(await loader.FetchWithCorsAsync(request, setting, behavior).ConfigureAwait(false));
                        }
                    }
                    else
                    {
                        return(result);
                    }
                }
            }
            else if (setting == CorsSetting.None)
            {
                if (behavior == OriginBehavior.Fail)
                {
                    throw new DomException(DomError.Network);
                }

                return(await loader.DownloadAsync(request).Task.ConfigureAwait(false));
            }
            else if (setting == CorsSetting.Anonymous || setting == CorsSetting.UseCredentials)
            {
                request.IsCredentialOmitted = setting == CorsSetting.Anonymous;
                var result = await loader.FetchAsync(request).ConfigureAwait(false);

                if (result != null && result.StatusCode == HttpStatusCode.OK)
                {
                    return(result);
                }
                else if (result != null)
                {
                    result.Dispose();
                }
            }

            throw new DomException(DomError.Network);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Performs a potentially CORS-enabled fetch from the given URI by
        /// using an asynchronous GET request. For more information see:
        /// http://www.w3.org/TR/html5/infrastructure.html#potentially-cors-enabled-fetch
        /// </summary>
        /// <param name="loader">The resource loader to use.</param>
        /// <param name="request">The request to issue.</param>
        /// <param name="setting">The cross origin settings to use.</param>
        /// <param name="behavior">
        /// The default behavior in case it is undefined.
        /// </param>
        /// <returns>
        /// The task which will eventually return the stream.
        /// </returns>
        public static async Task<IResponse> FetchWithCorsAsync(this IResourceLoader loader, ResourceRequest request, CorsSetting setting, OriginBehavior behavior)
        {
            var url = request.Target;

            if (request.Origin == url.Origin || url.Scheme == ProtocolNames.Data || url.Href == "about:blank")
            {
                while (true)
                {
                    var data = new ResourceRequest(request.Source, url)
                    {
                        Origin = request.Origin,
                        IsManualRedirectDesired = true
                    };

                    var result = await loader.DownloadAsync(data).Task.ConfigureAwait(false);

                    if (result.IsRedirected())
                    {
                        url = new Url(result.Headers.GetOrDefault(HeaderNames.Location, url.Href));

                        if (request.Origin.Is(url.Origin))
                        {
                            request = new ResourceRequest(request.Source, url)
                            {
                                IsCookieBlocked = request.IsCookieBlocked,
                                IsSameOriginForced = request.IsSameOriginForced,
                                Origin = request.Origin
                            };
                            return await loader.FetchWithCorsAsync(request, setting, behavior).ConfigureAwait(false);
                        }
                    }
                    else
                    {
                        return result;
                    }
                }
            }
            else if (setting == CorsSetting.None)
            {
                if (behavior == OriginBehavior.Fail)
                {
                    throw new DomException(DomError.Network);
                }

                return await loader.DownloadAsync(request).Task.ConfigureAwait(false);
            }
            else if (setting == CorsSetting.Anonymous || setting == CorsSetting.UseCredentials)
            {
                request.IsCredentialOmitted = setting == CorsSetting.Anonymous;
                var result = await loader.FetchAsync(request).ConfigureAwait(false);

                if (result != null && result.StatusCode == HttpStatusCode.OK)
                {
                    return result;
                }
                else if (result != null)
                {
                    result.Dispose();
                }
            }

            throw new DomException(DomError.Network);
        }
 /// <summary>
 /// Performs a potentially CORS-enabled fetch from the given URI by using an asynchronous GET request.
 /// </summary>
 /// <param name="configuration">The configuration to use.</param>
 /// <param name="url">The url that yields the path to the desired action.</param>
 /// <param name="cors">The cross origin settings to use.</param>
 /// <param name="origin">The origin of the page that requests the loading.</param>
 /// <param name="defaultBehavior">The default behavior in case it is undefined.</param>
 /// <returns>The task which will eventually return the stream.</returns>
 public static Task<Stream> LoadWithCorsAsync(this IConfiguration configuration, Url url, CorsSetting cors, String origin, OriginBehavior defaultBehavior)
 {
     return configuration.LoadWithCorsAsync(url, cors, origin, defaultBehavior, CancellationToken.None);
 }
        /// <summary>
        /// Performs a potentially CORS-enabled fetch from the given URI by using an asynchronous GET request.
        /// </summary>
        /// <param name="configuration">The configuration to use.</param>
        /// <param name="url">The url that yields the path to the desired action.</param>
        /// <param name="cors">The cross origin settings to use.</param>
        /// <param name="origin">The origin of the page that requests the loading.</param>
        /// <param name="defaultBehavior">The default behavior in case it is undefined.</param>
        /// <param name="cancel">The token which can be used to cancel the request.</param>
        /// <returns>The task which will eventually return the stream.</returns>
        public static async Task<Stream> LoadWithCorsAsync(this IConfiguration configuration, Url url, CorsSetting cors, String origin, OriginBehavior defaultBehavior, CancellationToken cancel)
        {
            if (!configuration.AllowRequests)
                return Stream.Null;

            var requester = configuration.GetRequester();

            if (requester == null)
                throw new NullReferenceException("No HTTP requester has been set up in the configuration.");

            var request = configuration.CreateRequest();

            if (request == null)
                throw new NullReferenceException("Unable to create instance of IRequest. Try changing the provided configuration.");

            request.Address = url;
            request.Method = HttpMethod.Get;
            //TODO
            //http://www.w3.org/TR/html5/infrastructure.html#potentially-cors-enabled-fetch
            var response = await requester.RequestAsync(request, cancel);
            return response.Content;
        }
Exemplo n.º 12
0
        static IDownload FetchWithCors(this IResourceLoader loader, ResourceRequest request, CorsSetting setting)
        {
            request.IsCredentialOmitted = setting == CorsSetting.Anonymous;
            var download = loader.DownloadAsync(request);

            return(download.Wrap(response =>
            {
                if (response != null && response.StatusCode == HttpStatusCode.OK)
                {
                    return download;
                }
                else if (response != null)
                {
                    response.Dispose();
                }

                throw new DomException(DomError.Network);
            }));
        }
Exemplo n.º 13
0
        static IDownload FetchWithCors(this IResourceLoader loader, Url url, ResourceRequest request, CorsSetting setting, OriginBehavior behavior)
        {
            var download = loader.DownloadAsync(new ResourceRequest(request.Source, url)
            {
                Origin = request.Origin,
                IsManualRedirectDesired = true
            });

            return(download.Wrap(response =>
            {
                if (response.IsRedirected())
                {
                    url.Href = response.Headers.GetOrDefault(HeaderNames.Location, url.Href);

                    if (request.Origin.Is(url.Origin))
                    {
                        return loader.FetchWithCors(new ResourceRequest(request.Source, url)
                        {
                            IsCookieBlocked = request.IsCookieBlocked,
                            IsSameOriginForced = request.IsSameOriginForced,
                            Origin = request.Origin
                        }, setting, behavior);
                    }

                    return loader.FetchWithCors(url, request, setting, behavior);
                }
                else
                {
                    return download;
                }
            }));
        }
Exemplo n.º 14
0
        /// <summary>
        /// Performs a potentially CORS-enabled fetch from the given URI by
        /// using an asynchronous GET request. For more information see:
        /// http://www.w3.org/TR/html5/infrastructure.html#potentially-cors-enabled-fetch
        /// </summary>
        /// <param name="loader">The resource loader to use.</param>
        /// <param name="request">The request to issue.</param>
        /// <param name="setting">The cross origin settings to use.</param>
        /// <param name="behavior">
        /// The default behavior in case it is undefined.
        /// </param>
        /// <returns>
        /// The task that will eventually give the resource's response data.
        /// </returns>
        public static IDownload FetchWithCors(this IResourceLoader loader, ResourceRequest request, CorsSetting setting, OriginBehavior behavior)
        {
            var url = request.Target;

            if (request.Origin == url.Origin || url.Scheme == ProtocolNames.Data || url.Href == "about:blank")
            {
                return(loader.FetchWithCors(url, request, setting, behavior));
            }
            else if (setting == CorsSetting.Anonymous || setting == CorsSetting.UseCredentials)
            {
                return(loader.FetchWithCors(request, setting));
            }
            else if (setting == CorsSetting.None)
            {
                return(loader.FetchWithoutCors(request, behavior));
            }

            throw new DomException(DomError.Network);
        }