Feature/use any id server for admin area (#232)

* initial commits around using any id servers

* add your own id server for admin area

* lots of refactoring, now instead of injecting IWebHostBuilder we just set the Ocelot base url as a configuration extension method..this means people can pass it in on the command line aswell as hardcode which is OK I guess, also can now use your own IdentityServer to authenticate admin area

* updated docs for #231

* some tests that hopefully bump up coverage
This commit is contained in:
Tom Pallister 2018-02-14 18:53:18 +00:00 committed by GitHub
parent 6f177fbf5b
commit 05481f3af3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
31 changed files with 876 additions and 546 deletions

View File

@ -1,8 +1,39 @@
Administration Administration
============== ==============
Ocelot supports changing configuration during runtime via an authenticated HTTP API. The API is authenticated Ocelot supports changing configuration during runtime via an authenticated HTTP API. This can be authenticated in two ways either using Ocelot's
using bearer tokens that you request from Ocelot iteself. This is provided by the amazing internal IdentityServer (for authenticating requests to the administration API only) or hooking the administration API authentication into your own
IdentityServer.
Providing your own IdentityServer
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
All you need to do to hook into your own IdentityServer is add the following to your ConfigureServices method.
.. code-block:: csharp
public virtual void ConfigureServices(IServiceCollection services)
{
Action<IdentityServerAuthenticationOptions> options = o => {
// o.Authority = ;
// o.ApiName = ;
// etc....
};
services
.AddOcelot(Configuration)
.AddAdministration("/administration", options);
}
You now need to get a token from your IdentityServer and use in subsequent requests to Ocelot's administration API.
This feature was implemented for `issue 228 <https://github.com/TomPallister/Ocelot/issues/228>`_. It is useful because the IdentityServer authentication
middleware needs the URL of the IdentityServer. If you are using the internal IdentityServer it might not alaways be possible to have the Ocelot URL.
Internal IdentityServer
^^^^^^^^^^^^^^^^^^^^^^^
The API is authenticated using bearer tokens that you request from Ocelot iteself. This is provided by the amazing
`Identity Server <https://github.com/IdentityServer/IdentityServer4>`_ project that I have been using for a few years now. Check them out. `Identity Server <https://github.com/IdentityServer/IdentityServer4>`_ project that I have been using for a few years now. Check them out.
In order to enable the administration section you need to do a few things. First of all add this to your In order to enable the administration section you need to do a few things. First of all add this to your
@ -31,8 +62,6 @@ will need to be changed if you are running Ocelot on a different url to http://l
The scripts show you how to request a bearer token from ocelot and then use it to GET the existing configuration and POST The scripts show you how to request a bearer token from ocelot and then use it to GET the existing configuration and POST
a configuration. a configuration.
Administration running multiple Ocelot's
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
If you are running multiple Ocelot's in a cluster then you need to use a certificate to sign the bearer tokens used to access the administration API. If you are running multiple Ocelot's in a cluster then you need to use a certificate to sign the bearer tokens used to access the administration API.
In order to do this you need to add two more environmental variables for each Ocelot in the cluster. In order to do this you need to add two more environmental variables for each Ocelot in the cluster.
@ -44,6 +73,7 @@ In order to do this you need to add two more environmental variables for each Oc
Normally Ocelot just uses temporary signing credentials but if you set these environmental variables then it will use the certificate. If all the other Ocelots in the cluster have the same certificate then you are good! Normally Ocelot just uses temporary signing credentials but if you set these environmental variables then it will use the certificate. If all the other Ocelots in the cluster have the same certificate then you are good!
Administration API Administration API
^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^

View File

@ -135,3 +135,10 @@ Then map the authentication provider key to a ReRoute in your configuration e.g.
"AllowedScopes": [] "AllowedScopes": []
} }
}] }]
Allowed Scopes
^^^^^^^^^^^^^
If you add scopes to AllowedScopes Ocelot will get all the user claims (from the token) of the type scope and make sure that the user has all of the scopes in the list.
This is a way to restrict access to a ReRoute on a per scope basis.

View File

@ -29,8 +29,8 @@ The following is a very basic configuration.json. It won't do anything but shoul
**Program** **Program**
Then in your Program.cs you will want to have the following. This can be changed if you Then in your Program.cs you will want to have the following. The main things to note are AddOcelotBaseUrl("http://localhost:5000") (adds the url this instance of Ocelot will run under),
don't wan't to use the default url e.g. UseUrls(someUrls) and should work as long as you keep the WebHostBuilder registration. AddOcelot() (adds ocelot services), UseOcelot().Wait() (sets up all the Ocelot middleware). It is important to call AddOcelotBaseUrl as Ocelot needs to know the URL that it is exposed to the outside world on.
.. code-block:: csharp .. code-block:: csharp
@ -38,51 +38,33 @@ don't wan't to use the default url e.g. UseUrls(someUrls) and should work as lon
{ {
public static void Main(string[] args) public static void Main(string[] args)
{ {
IWebHostBuilder builder = new WebHostBuilder(); new WebHostBuilder()
builder.ConfigureServices(s => { .UseKestrel()
s.AddSingleton(builder);
});
builder.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory()) .UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) => .ConfigureAppConfiguration((hostingContext, config) =>
{ {
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath); config
var env = hostingContext.HostingEnvironment; .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
config.AddJsonFile("configuration.json"); .AddJsonFile("configuration.json")
config.AddEnvironmentVariables(); .AddEnvironmentVariables()
.AddOcelotBaseUrl("http://localhost:5000");
})
.ConfigureServices(s => {
s.AddOcelot();
}) })
.ConfigureLogging((hostingContext, logging) => .ConfigureLogging((hostingContext, logging) =>
{ {
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); //add your logging
logging.AddConsole();
}) })
.UseIISIntegration() .UseIISIntegration()
.UseStartup<ManualTestStartup>(); .Configure(app =>
var host = builder.Build(); {
host.Run(); app.UseOcelot().Wait();
} })
} .Build()
.Run();
Sadly we need to inject the IWebHostBuilder interface to get the applications scheme, url and port later. I cannot find a better way of doing this at the moment without setting this in a static or some kind of config.
**Startup**
An example startup using a json file for configuration can be seen below. This is the most basic startup and Ocelot has quite a few more options. Detailed in the rest of these docs! If you get a stuck a good place to look is at the ManualTests project in the source code.
.. code-block:: csharp
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddOcelot();
}
public void Configure(IApplicationBuilder app)
{
app.UseOcelot().Wait();
} }
} }
@ -109,8 +91,7 @@ The following is a very basic configuration.json. It won't do anything but shoul
**Program** **Program**
Then in your Program.cs you will want to have the following. This can be changed if you Then in your Program.cs you will want to have the following.
don't wan't to use the default url e.g. UseUrls(someUrls) and should work as long as you keep the WebHostBuilder registration.
.. code-block:: csharp .. code-block:: csharp
@ -121,7 +102,6 @@ don't wan't to use the default url e.g. UseUrls(someUrls) and should work as lon
IWebHostBuilder builder = new WebHostBuilder(); IWebHostBuilder builder = new WebHostBuilder();
builder.ConfigureServices(s => { builder.ConfigureServices(s => {
s.AddSingleton(builder);
}); });
builder.UseKestrel() builder.UseKestrel()
@ -134,8 +114,6 @@ don't wan't to use the default url e.g. UseUrls(someUrls) and should work as lon
} }
} }
Sadly we need to inject the IWebHostBuilder interface to get the applications scheme, url and port later. I cannot find a better way of doing this at the moment without setting this in a static or some kind of config.
**Startup** **Startup**
An example startup using a json file for configuration can be seen below. An example startup using a json file for configuration can be seen below.
@ -151,7 +129,8 @@ An example startup using a json file for configuration can be seen below.
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddJsonFile("configuration.json") .AddJsonFile("configuration.json")
.AddEnvironmentVariables(); .AddEnvironmentVariables()
.AddOcelotBaseUrl("http://localhost:5000");
Configuration = builder.Build(); Configuration = builder.Build();
} }

View File

@ -8,15 +8,13 @@ namespace Ocelot.Configuration.Creator
public class HeaderFindAndReplaceCreator : IHeaderFindAndReplaceCreator public class HeaderFindAndReplaceCreator : IHeaderFindAndReplaceCreator
{ {
private IBaseUrlFinder _finder; private IBaseUrlFinder _finder;
private Dictionary<string, Func<string>> _placeholders; private readonly Dictionary<string, Func<string>> _placeholders;
public HeaderFindAndReplaceCreator(IBaseUrlFinder finder) public HeaderFindAndReplaceCreator(IBaseUrlFinder finder)
{ {
_finder = finder; _finder = finder;
_placeholders = new Dictionary<string, Func<string>>(); _placeholders = new Dictionary<string, Func<string>>();
_placeholders.Add("{BaseUrl}", () => { _placeholders.Add("{BaseUrl}", () => _finder.Find());
return _finder.Find();
});
} }
public HeaderTransformations Create(FileReRoute fileReRoute) public HeaderTransformations Create(FileReRoute fileReRoute)

View File

@ -0,0 +1,20 @@
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Memory;
namespace Ocelot.DependencyInjection
{
public static class ConfigurationBuilderExtensions
{
public static IConfigurationBuilder AddOcelotBaseUrl(this IConfigurationBuilder builder, string baseUrl)
{
var memorySource = new MemoryConfigurationSource();
memorySource.InitialData = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("BaseUrl", baseUrl)
};
builder.Add(memorySource);
return builder;
}
}
}

View File

@ -2,6 +2,7 @@ using Butterfly.Client.AspNetCore;
using CacheManager.Core; using CacheManager.Core;
using System; using System;
using System.Net.Http; using System.Net.Http;
using IdentityServer4.AccessTokenValidation;
namespace Ocelot.DependencyInjection namespace Ocelot.DependencyInjection
{ {
@ -11,6 +12,7 @@ namespace Ocelot.DependencyInjection
IOcelotBuilder AddCacheManager(Action<ConfigurationBuilderCachePart> settings); IOcelotBuilder AddCacheManager(Action<ConfigurationBuilderCachePart> settings);
IOcelotBuilder AddOpenTracing(Action<ButterflyOptions> settings); IOcelotBuilder AddOpenTracing(Action<ButterflyOptions> settings);
IOcelotAdministrationBuilder AddAdministration(string path, string secret); IOcelotAdministrationBuilder AddAdministration(string path, string secret);
IOcelotAdministrationBuilder AddAdministration(string path, Action<IdentityServerAuthenticationOptions> configOptions);
IOcelotBuilder AddDelegatingHandler(Func<DelegatingHandler> delegatingHandler); IOcelotBuilder AddDelegatingHandler(Func<DelegatingHandler> delegatingHandler);
} }
} }

View File

@ -1,60 +1,62 @@
using CacheManager.Core; using Microsoft.Extensions.Options;
using IdentityServer4.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Ocelot.Authorisation;
using Ocelot.Cache;
using Ocelot.Claims;
using Ocelot.Configuration.Authentication;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File;
using Ocelot.Configuration.Parser;
using Ocelot.Configuration.Provider;
using Ocelot.Configuration.Repository;
using Ocelot.Configuration.Setter;
using Ocelot.Configuration.Validator;
using Ocelot.DownstreamRouteFinder.Finder;
using Ocelot.DownstreamRouteFinder.UrlMatcher;
using Ocelot.DownstreamUrlCreator;
using Ocelot.DownstreamUrlCreator.UrlTemplateReplacer;
using Ocelot.Headers;
using Ocelot.Infrastructure.Claims.Parser;
using Ocelot.Infrastructure.RequestData;
using Ocelot.LoadBalancer.LoadBalancers;
using Ocelot.Logging;
using Ocelot.Middleware;
using Ocelot.QueryStrings;
using Ocelot.RateLimit;
using Ocelot.Request.Builder;
using Ocelot.Request.Mapper;
using Ocelot.Requester;
using Ocelot.Requester.QoS;
using Ocelot.Responder;
using Ocelot.ServiceDiscovery;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using IdentityServer4.AccessTokenValidation;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using FileConfigurationProvider = Ocelot.Configuration.Provider.FileConfigurationProvider;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System.Linq;
using System.Net.Http;
using Butterfly.Client.AspNetCore;
namespace Ocelot.DependencyInjection namespace Ocelot.DependencyInjection
{ {
using CacheManager.Core;
using IdentityServer4.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Ocelot.Authorisation;
using Ocelot.Cache;
using Ocelot.Claims;
using Ocelot.Configuration.Authentication;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File;
using Ocelot.Configuration.Parser;
using Ocelot.Configuration.Provider;
using Ocelot.Configuration.Repository;
using Ocelot.Configuration.Setter;
using Ocelot.Configuration.Validator;
using Ocelot.DownstreamRouteFinder.Finder;
using Ocelot.DownstreamRouteFinder.UrlMatcher;
using Ocelot.DownstreamUrlCreator;
using Ocelot.DownstreamUrlCreator.UrlTemplateReplacer;
using Ocelot.Headers;
using Ocelot.Infrastructure.Claims.Parser;
using Ocelot.Infrastructure.RequestData;
using Ocelot.LoadBalancer.LoadBalancers;
using Ocelot.Logging;
using Ocelot.Middleware;
using Ocelot.QueryStrings;
using Ocelot.RateLimit;
using Ocelot.Request.Builder;
using Ocelot.Request.Mapper;
using Ocelot.Requester;
using Ocelot.Requester.QoS;
using Ocelot.Responder;
using Ocelot.ServiceDiscovery;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using IdentityServer4.AccessTokenValidation;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using FileConfigurationProvider = Ocelot.Configuration.Provider.FileConfigurationProvider;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System.Linq;
using System.Net.Http;
using Butterfly.Client.AspNetCore;
public class OcelotBuilder : IOcelotBuilder public class OcelotBuilder : IOcelotBuilder
{ {
private readonly IServiceCollection _services; private readonly IServiceCollection _services;
private readonly IConfiguration _configurationRoot; private readonly IConfiguration _configurationRoot;
private IDelegatingHandlerHandlerProvider _provider; private readonly IDelegatingHandlerHandlerProvider _provider;
public OcelotBuilder(IServiceCollection services, IConfiguration configurationRoot) public OcelotBuilder(IServiceCollection services, IConfiguration configurationRoot)
{ {
@ -109,7 +111,7 @@ namespace Ocelot.DependencyInjection
_services.TryAddSingleton<IUrlPathToUrlTemplateMatcher, RegExUrlMatcher>(); _services.TryAddSingleton<IUrlPathToUrlTemplateMatcher, RegExUrlMatcher>();
_services.TryAddSingleton<IPlaceholderNameAndValueFinder, UrlPathPlaceholderNameAndValueFinder>(); _services.TryAddSingleton<IPlaceholderNameAndValueFinder, UrlPathPlaceholderNameAndValueFinder>();
_services.TryAddSingleton<IDownstreamPathPlaceholderReplacer, DownstreamTemplatePathPlaceholderReplacer>(); _services.TryAddSingleton<IDownstreamPathPlaceholderReplacer, DownstreamTemplatePathPlaceholderReplacer>();
_services.TryAddSingleton<IDownstreamRouteFinder, DownstreamRouteFinder.Finder.DownstreamRouteFinder>(); _services.TryAddSingleton<IDownstreamRouteFinder, DownstreamRouteFinder>();
_services.TryAddSingleton<IHttpRequester, HttpClientHttpRequester>(); _services.TryAddSingleton<IHttpRequester, HttpClientHttpRequester>();
_services.TryAddSingleton<IHttpResponder, HttpContextResponder>(); _services.TryAddSingleton<IHttpResponder, HttpContextResponder>();
_services.TryAddSingleton<IRequestCreator, HttpRequestCreator>(); _services.TryAddSingleton<IRequestCreator, HttpRequestCreator>();
@ -166,6 +168,21 @@ namespace Ocelot.DependencyInjection
return new OcelotAdministrationBuilder(_services, _configurationRoot); return new OcelotAdministrationBuilder(_services, _configurationRoot);
} }
public IOcelotAdministrationBuilder AddAdministration(string path, Action<IdentityServerAuthenticationOptions> configureOptions)
{
var administrationPath = new AdministrationPath(path);
if (configureOptions != null)
{
AddIdentityServer(configureOptions);
}
//todo - hack because we add this earlier so it always exists for some reason...investigate..
var descriptor = new ServiceDescriptor(typeof(IAdministrationPath), administrationPath);
_services.Replace(descriptor);
return new OcelotAdministrationBuilder(_services, _configurationRoot);
}
public IOcelotBuilder AddDelegatingHandler(Func<DelegatingHandler> delegatingHandler) public IOcelotBuilder AddDelegatingHandler(Func<DelegatingHandler> delegatingHandler)
{ {
_provider.Add(delegatingHandler); _provider.Add(delegatingHandler);
@ -221,6 +238,13 @@ namespace Ocelot.DependencyInjection
return this; return this;
} }
private void AddIdentityServer(Action<IdentityServerAuthenticationOptions> configOptions)
{
_services
.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(configOptions);
}
private void AddIdentityServer(IIdentityServerConfiguration identityServerConfiguration, IAdministrationPath adminPath) private void AddIdentityServer(IIdentityServerConfiguration identityServerConfiguration, IAdministrationPath adminPath)
{ {
_services.TryAddSingleton<IIdentityServerConfiguration>(identityServerConfiguration); _services.TryAddSingleton<IIdentityServerConfiguration>(identityServerConfiguration);
@ -232,12 +256,11 @@ namespace Ocelot.DependencyInjection
.AddInMemoryApiResources(Resources(identityServerConfiguration)) .AddInMemoryApiResources(Resources(identityServerConfiguration))
.AddInMemoryClients(Client(identityServerConfiguration)); .AddInMemoryClients(Client(identityServerConfiguration));
//todo - refactor a method so we know why this is happening var urlFinder = new BaseUrlFinder(_configurationRoot);
var whb = _services.First(x => x.ServiceType == typeof(IWebHostBuilder));
var urlFinder = new BaseUrlFinder((IWebHostBuilder)whb.ImplementationInstance);
var baseSchemeUrlAndPort = urlFinder.Find(); var baseSchemeUrlAndPort = urlFinder.Find();
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
_services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) _services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(o => .AddIdentityServerAuthentication(o =>
{ {

View File

@ -1,6 +1,6 @@
using Microsoft.Extensions.Configuration; using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System.Linq; using System.Linq;
namespace Ocelot.DependencyInjection namespace Ocelot.DependencyInjection

View File

@ -21,7 +21,6 @@ namespace Ocelot.Errors.Middleware
private readonly IRequestScopedDataRepository _requestScopedDataRepository; private readonly IRequestScopedDataRepository _requestScopedDataRepository;
private readonly IOcelotConfigurationProvider _configProvider; private readonly IOcelotConfigurationProvider _configProvider;
public ExceptionHandlerMiddleware(RequestDelegate next, public ExceptionHandlerMiddleware(RequestDelegate next,
IOcelotLoggerFactory loggerFactory, IOcelotLoggerFactory loggerFactory,
IRequestScopedDataRepository requestScopedDataRepository, IRequestScopedDataRepository requestScopedDataRepository,

View File

@ -1,21 +1,21 @@
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration;
namespace Ocelot.Middleware namespace Ocelot.Middleware
{ {
public class BaseUrlFinder : IBaseUrlFinder public class BaseUrlFinder : IBaseUrlFinder
{ {
private readonly IWebHostBuilder _webHostBuilder; private readonly IConfiguration _config;
public BaseUrlFinder(IWebHostBuilder webHostBuilder) public BaseUrlFinder(IConfiguration config)
{ {
_webHostBuilder = webHostBuilder; _config = config;
} }
public string Find() public string Find()
{ {
var baseSchemeUrlAndPort = _webHostBuilder.GetSetting(WebHostDefaults.ServerUrlsKey); var baseUrl = _config.GetValue("BaseUrl", "");
return string.IsNullOrEmpty(baseSchemeUrlAndPort) ? "http://localhost:5000" : baseSchemeUrlAndPort; return string.IsNullOrEmpty(baseUrl) ? "http://localhost:5000" : baseUrl;
} }
} }
} }

View File

@ -1,36 +1,14 @@
using System.Collections.Generic; namespace Ocelot.Middleware
using System.Diagnostics;
using System.Reflection;
using IdentityServer4.AccessTokenValidation;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Ocelot.Authentication.Middleware;
using Ocelot.Cache.Middleware;
using Ocelot.Claims.Middleware;
using Ocelot.DownstreamRouteFinder.Middleware;
using Ocelot.DownstreamUrlCreator.Middleware;
using Ocelot.Errors.Middleware;
using Ocelot.Headers.Middleware;
using Ocelot.Logging;
using Ocelot.QueryStrings.Middleware;
using Ocelot.Request.Middleware;
using Ocelot.Requester.Middleware;
using Ocelot.RequestId.Middleware;
using Ocelot.Responder.Middleware;
using Ocelot.RateLimit.Middleware;
namespace Ocelot.Middleware
{ {
using System; using System;
using System.IO;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Authorisation.Middleware; using Authorisation.Middleware;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Newtonsoft.Json; using System.Diagnostics;
using Microsoft.AspNetCore.Builder;
using Ocelot.Configuration; using Ocelot.Configuration;
using Ocelot.Configuration.Creator; using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File; using Ocelot.Configuration.File;
@ -38,8 +16,21 @@ namespace Ocelot.Middleware
using Ocelot.Configuration.Repository; using Ocelot.Configuration.Repository;
using Ocelot.Configuration.Setter; using Ocelot.Configuration.Setter;
using Ocelot.LoadBalancer.Middleware; using Ocelot.LoadBalancer.Middleware;
using Ocelot.Raft;
using Ocelot.Responses; using Ocelot.Responses;
using Ocelot.Authentication.Middleware;
using Ocelot.Cache.Middleware;
using Ocelot.Claims.Middleware;
using Ocelot.DownstreamRouteFinder.Middleware;
using Ocelot.DownstreamUrlCreator.Middleware;
using Ocelot.Errors.Middleware;
using Ocelot.Headers.Middleware;
using Ocelot.Logging;
using Ocelot.QueryStrings.Middleware;
using Ocelot.Request.Middleware;
using Ocelot.Requester.Middleware;
using Ocelot.RequestId.Middleware;
using Ocelot.Responder.Middleware;
using Ocelot.RateLimit.Middleware;
using Rafty.Concensus; using Rafty.Concensus;
using Rafty.Infrastructure; using Rafty.Infrastructure;
@ -67,7 +58,7 @@ namespace Ocelot.Middleware
{ {
var configuration = await CreateConfiguration(builder); var configuration = await CreateConfiguration(builder);
await CreateAdministrationArea(builder, configuration); CreateAdministrationArea(builder, configuration);
if(UsingRafty(builder)) if(UsingRafty(builder))
{ {
@ -290,15 +281,19 @@ namespace Ocelot.Middleware
return new OkResponse(); return new OkResponse();
} }
private static async Task CreateAdministrationArea(IApplicationBuilder builder, IOcelotConfiguration configuration) private static void CreateAdministrationArea(IApplicationBuilder builder, IOcelotConfiguration configuration)
{ {
var identityServerConfiguration = (IIdentityServerConfiguration)builder.ApplicationServices.GetService(typeof(IIdentityServerConfiguration)); if(!string.IsNullOrEmpty(configuration.AdministrationPath))
if(!string.IsNullOrEmpty(configuration.AdministrationPath) && identityServerConfiguration != null)
{ {
builder.Map(configuration.AdministrationPath, app => builder.Map(configuration.AdministrationPath, app =>
{ {
app.UseIdentityServer(); //todo - hack so we know that we are using internal identity server
var identityServerConfiguration = (IIdentityServerConfiguration)builder.ApplicationServices.GetService(typeof(IIdentityServerConfiguration));
if (identityServerConfiguration != null)
{
app.UseIdentityServer();
}
app.UseAuthentication(); app.UseAuthentication();
app.UseMvc(); app.UseMvc();
}); });

View File

@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Ocelot.Configuration; using Ocelot.Configuration;
using Ocelot.Configuration.Provider; using Ocelot.Configuration.Provider;
using Ocelot.Middleware;
using Rafty.Concensus; using Rafty.Concensus;
using Rafty.Infrastructure; using Rafty.Infrastructure;
@ -15,15 +16,15 @@ namespace Ocelot.Raft
{ {
private readonly IOptions<FilePeers> _options; private readonly IOptions<FilePeers> _options;
private List<IPeer> _peers; private List<IPeer> _peers;
private IWebHostBuilder _builder; private IBaseUrlFinder _finder;
private IOcelotConfigurationProvider _provider; private IOcelotConfigurationProvider _provider;
private IIdentityServerConfiguration _identityServerConfig; private IIdentityServerConfiguration _identityServerConfig;
public FilePeersProvider(IOptions<FilePeers> options, IWebHostBuilder builder, IOcelotConfigurationProvider provider, IIdentityServerConfiguration identityServerConfig) public FilePeersProvider(IOptions<FilePeers> options, IBaseUrlFinder finder, IOcelotConfigurationProvider provider, IIdentityServerConfiguration identityServerConfig)
{ {
_identityServerConfig = identityServerConfig; _identityServerConfig = identityServerConfig;
_provider = provider; _provider = provider;
_builder = builder; _finder = finder;
_options = options; _options = options;
_peers = new List<IPeer>(); _peers = new List<IPeer>();
//todo - sort out async nonsense.. //todo - sort out async nonsense..
@ -32,7 +33,7 @@ namespace Ocelot.Raft
{ {
var httpClient = new HttpClient(); var httpClient = new HttpClient();
//todo what if this errors? //todo what if this errors?
var httpPeer = new HttpPeer(item.HostAndPort, httpClient, _builder, config.Data, _identityServerConfig); var httpPeer = new HttpPeer(item.HostAndPort, httpClient, _finder, config.Data, _identityServerConfig);
_peers.Add(httpPeer); _peers.Add(httpPeer);
} }
} }

View File

@ -7,6 +7,7 @@ using Newtonsoft.Json;
using Ocelot.Authentication; using Ocelot.Authentication;
using Ocelot.Configuration; using Ocelot.Configuration;
using Ocelot.Configuration.Provider; using Ocelot.Configuration.Provider;
using Ocelot.Middleware;
using Rafty.Concensus; using Rafty.Concensus;
using Rafty.FiniteStateMachine; using Rafty.FiniteStateMachine;
@ -23,7 +24,7 @@ namespace Ocelot.Raft
private IOcelotConfiguration _config; private IOcelotConfiguration _config;
private IIdentityServerConfiguration _identityServerConfiguration; private IIdentityServerConfiguration _identityServerConfiguration;
public HttpPeer(string hostAndPort, HttpClient httpClient, IWebHostBuilder builder, IOcelotConfiguration config, IIdentityServerConfiguration identityServerConfiguration) public HttpPeer(string hostAndPort, HttpClient httpClient, IBaseUrlFinder finder, IOcelotConfiguration config, IIdentityServerConfiguration identityServerConfiguration)
{ {
_identityServerConfiguration = identityServerConfiguration; _identityServerConfiguration = identityServerConfiguration;
_config = config; _config = config;
@ -33,7 +34,7 @@ namespace Ocelot.Raft
_jsonSerializerSettings = new JsonSerializerSettings() { _jsonSerializerSettings = new JsonSerializerSettings() {
TypeNameHandling = TypeNameHandling.All TypeNameHandling = TypeNameHandling.All
}; };
_baseSchemeUrlAndPort = builder.GetSetting(WebHostDefaults.ServerUrlsKey); _baseSchemeUrlAndPort = finder.Find();
} }
public string Id {get; private set;} public string Id {get; private set;}

View File

@ -7,6 +7,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json; using Newtonsoft.Json;
using Ocelot.Logging; using Ocelot.Logging;
using Ocelot.Middleware;
using Ocelot.Raft; using Ocelot.Raft;
using Rafty.Concensus; using Rafty.Concensus;
using Rafty.FiniteStateMachine; using Rafty.FiniteStateMachine;
@ -23,12 +24,12 @@ namespace Ocelot.Raft
private string _baseSchemeUrlAndPort; private string _baseSchemeUrlAndPort;
private JsonSerializerSettings _jsonSerialiserSettings; private JsonSerializerSettings _jsonSerialiserSettings;
public RaftController(INode node, IOcelotLoggerFactory loggerFactory, IWebHostBuilder builder) public RaftController(INode node, IOcelotLoggerFactory loggerFactory, IBaseUrlFinder finder)
{ {
_jsonSerialiserSettings = new JsonSerializerSettings { _jsonSerialiserSettings = new JsonSerializerSettings {
TypeNameHandling = TypeNameHandling.All TypeNameHandling = TypeNameHandling.All
}; };
_baseSchemeUrlAndPort = builder.GetSetting(WebHostDefaults.ServerUrlsKey); _baseSchemeUrlAndPort = finder.Find();
_logger = loggerFactory.CreateLogger<RaftController>(); _logger = loggerFactory.CreateLogger<RaftController>();
_node = node; _node = node;
} }

View File

@ -1,39 +0,0 @@
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using ConfigurationBuilder = Microsoft.Extensions.Configuration.ConfigurationBuilder;
namespace Ocelot.AcceptanceTests
{
public class AcceptanceTestsStartup
{
public AcceptanceTestsStartup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddJsonFile("configuration.json")
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
public virtual void ConfigureServices(IServiceCollection services)
{
services.AddOcelot(Configuration);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseOcelot().Wait();
}
}
}

View File

@ -1,40 +0,0 @@
using System;
using CacheManager.Core;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using ConfigurationBuilder = Microsoft.Extensions.Configuration.ConfigurationBuilder;
namespace Ocelot.AcceptanceTests
{
public class ConsulStartup
{
public ConsulStartup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddJsonFile("configuration.json")
.AddEnvironmentVariables();
Config = builder.Build();
}
public static IConfiguration Config { get; private set; }
public void ConfigureServices(IServiceCollection services)
{
services.AddOcelot(Config).AddStoreOcelotConfigurationInConsul();
}
public void Configure(IApplicationBuilder app)
{
app.UseOcelot().Wait();
}
}
}

View File

@ -1,29 +0,0 @@
using CacheManager.Core;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Ocelot.DependencyInjection;
using Ocelot.AcceptanceTests.Caching;
namespace Ocelot.AcceptanceTests
{
public class StartupWithConsulAndCustomCacheHandle : AcceptanceTestsStartup
{
public StartupWithConsulAndCustomCacheHandle(IHostingEnvironment env) : base(env) { }
public override void ConfigureServices(IServiceCollection services)
{
services.AddOcelot(Configuration)
.AddCacheManager((x) =>
{
x.WithMicrosoftLogging(log =>
{
log.AddConsole(LogLevel.Debug);
})
.WithJsonSerializer()
.WithHandle(typeof(InMemoryJsonHandle<>));
})
.AddStoreOcelotConfigurationInConsul();
}
}
}

View File

@ -1,28 +0,0 @@
using CacheManager.Core;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Ocelot.DependencyInjection;
using Ocelot.AcceptanceTests.Caching;
namespace Ocelot.AcceptanceTests
{
public class StartupWithCustomCacheHandle : AcceptanceTestsStartup
{
public StartupWithCustomCacheHandle(IHostingEnvironment env) : base(env) { }
public override void ConfigureServices(IServiceCollection services)
{
services.AddOcelot(Configuration)
.AddCacheManager((x) =>
{
x.WithMicrosoftLogging(log =>
{
log.AddConsole(LogLevel.Debug);
})
.WithJsonSerializer()
.WithHandle(typeof(InMemoryJsonHandle<>));
});
}
}
}

View File

@ -38,9 +38,11 @@ namespace Ocelot.AcceptanceTests
public string RequestIdKey = "OcRequestId"; public string RequestIdKey = "OcRequestId";
private readonly Random _random; private readonly Random _random;
private IWebHostBuilder _webHostBuilder; private IWebHostBuilder _webHostBuilder;
private readonly string _baseUrl;
public Steps() public Steps()
{ {
_baseUrl = "http://localhost:5000";
_random = new Random(); _random = new Random();
} }
@ -77,13 +79,26 @@ namespace Ocelot.AcceptanceTests
{ {
_webHostBuilder = new WebHostBuilder(); _webHostBuilder = new WebHostBuilder();
_webHostBuilder.ConfigureServices(s => _webHostBuilder
{ .ConfigureAppConfiguration((hostingContext, config) =>
s.AddSingleton(_webHostBuilder); {
}); config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
config.AddJsonFile("configuration.json");
config.AddEnvironmentVariables();
})
.ConfigureServices(s =>
{
s.AddOcelot();
})
.Configure(app =>
{
app.UseOcelot().Wait();
});
_ocelotServer = new TestServer(_webHostBuilder _ocelotServer = new TestServer(_webHostBuilder);
.UseStartup<AcceptanceTestsStartup>());
_ocelotClient = _ocelotServer.CreateClient(); _ocelotClient = _ocelotServer.CreateClient();
} }
@ -95,25 +110,27 @@ namespace Ocelot.AcceptanceTests
{ {
_webHostBuilder = new WebHostBuilder(); _webHostBuilder = new WebHostBuilder();
_webHostBuilder.ConfigureServices(s => _webHostBuilder
{ .ConfigureAppConfiguration((hostingContext, config) =>
s.AddSingleton(_webHostBuilder); {
s.AddOcelot() config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
.AddDelegatingHandler(() => handlerOne) var env = hostingContext.HostingEnvironment;
.AddDelegatingHandler(() => handlerTwo); config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
}); .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
_webHostBuilder.ConfigureAppConfiguration((hostingContext, config) => config.AddJsonFile("configuration.json");
{ config.AddEnvironmentVariables();
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath); })
var env = hostingContext.HostingEnvironment; .ConfigureServices(s =>
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) {
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); s.AddSingleton(_webHostBuilder);
config.AddJsonFile("configuration.json"); s.AddOcelot()
config.AddEnvironmentVariables(); .AddDelegatingHandler(() => handlerOne)
}).Configure(a => .AddDelegatingHandler(() => handlerTwo);
{ })
a.UseOcelot().Wait(); .Configure(a =>
}); {
a.UseOcelot().Wait();
});
_ocelotServer = new TestServer(_webHostBuilder); _ocelotServer = new TestServer(_webHostBuilder);
@ -127,15 +144,29 @@ namespace Ocelot.AcceptanceTests
{ {
_webHostBuilder = new WebHostBuilder(); _webHostBuilder = new WebHostBuilder();
_webHostBuilder.ConfigureServices(s => _webHostBuilder
{ .ConfigureAppConfiguration((hostingContext, config) =>
s.AddSingleton(_webHostBuilder); {
s.AddAuthentication() config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
.AddIdentityServerAuthentication(authenticationProviderKey, options); var env = hostingContext.HostingEnvironment;
}); config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
config.AddJsonFile("configuration.json");
config.AddOcelotBaseUrl(_baseUrl);
config.AddEnvironmentVariables();
})
.ConfigureServices(s =>
{
s.AddOcelot();
s.AddAuthentication()
.AddIdentityServerAuthentication(authenticationProviderKey, options);
})
.Configure(app =>
{
app.UseOcelot().Wait();
});
_ocelotServer = new TestServer(_webHostBuilder _ocelotServer = new TestServer(_webHostBuilder);
.UseStartup<AcceptanceTestsStartup>());
_ocelotClient = _ocelotServer.CreateClient(); _ocelotClient = _ocelotServer.CreateClient();
} }
@ -150,13 +181,36 @@ namespace Ocelot.AcceptanceTests
{ {
_webHostBuilder = new WebHostBuilder(); _webHostBuilder = new WebHostBuilder();
_webHostBuilder.ConfigureServices(s => _webHostBuilder
{ .ConfigureAppConfiguration((hostingContext, config) =>
s.AddSingleton(_webHostBuilder); {
}); config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
config.AddJsonFile("configuration.json");
config.AddOcelotBaseUrl(_baseUrl);
config.AddEnvironmentVariables();
})
.ConfigureServices(s =>
{
s.AddOcelot()
.AddCacheManager((x) =>
{
x.WithMicrosoftLogging(log =>
{
log.AddConsole(LogLevel.Debug);
})
.WithJsonSerializer()
.WithHandle(typeof(InMemoryJsonHandle<>));
});
})
.Configure(app =>
{
app.UseOcelot().Wait();
});
_ocelotServer = new TestServer(_webHostBuilder _ocelotServer = new TestServer(_webHostBuilder);
.UseStartup<StartupWithCustomCacheHandle>());
_ocelotClient = _ocelotServer.CreateClient(); _ocelotClient = _ocelotServer.CreateClient();
} }
@ -165,13 +219,27 @@ namespace Ocelot.AcceptanceTests
{ {
_webHostBuilder = new WebHostBuilder(); _webHostBuilder = new WebHostBuilder();
_webHostBuilder.ConfigureServices(s => _webHostBuilder
{ .ConfigureAppConfiguration((hostingContext, config) =>
s.AddSingleton(_webHostBuilder); {
}); config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
config.AddJsonFile("configuration.json");
config.AddOcelotBaseUrl(_baseUrl);
config.AddEnvironmentVariables();
})
.ConfigureServices(s =>
{
s.AddOcelot().AddStoreOcelotConfigurationInConsul();
})
.Configure(app =>
{
app.UseOcelot().Wait();
});
_ocelotServer = new TestServer(_webHostBuilder _ocelotServer = new TestServer(_webHostBuilder);
.UseStartup<ConsulStartup>());
_ocelotClient = _ocelotServer.CreateClient(); _ocelotClient = _ocelotServer.CreateClient();
} }
@ -180,13 +248,37 @@ namespace Ocelot.AcceptanceTests
{ {
_webHostBuilder = new WebHostBuilder(); _webHostBuilder = new WebHostBuilder();
_webHostBuilder.ConfigureServices(s => _webHostBuilder
{ .ConfigureAppConfiguration((hostingContext, config) =>
s.AddSingleton(_webHostBuilder); {
}); config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
config.AddJsonFile("configuration.json");
config.AddOcelotBaseUrl(_baseUrl);
config.AddEnvironmentVariables();
})
.ConfigureServices(s =>
{
s.AddOcelot()
.AddCacheManager((x) =>
{
x.WithMicrosoftLogging(log =>
{
log.AddConsole(LogLevel.Debug);
})
.WithJsonSerializer()
.WithHandle(typeof(InMemoryJsonHandle<>));
})
.AddStoreOcelotConfigurationInConsul();
})
.Configure(app =>
{
app.UseOcelot().Wait();
});
_ocelotServer = new TestServer(_webHostBuilder _ocelotServer = new TestServer(_webHostBuilder);
.UseStartup<StartupWithConsulAndCustomCacheHandle>());
_ocelotClient = _ocelotServer.CreateClient(); _ocelotClient = _ocelotServer.CreateClient();
} }

View File

@ -4,11 +4,21 @@ using System.IO;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Security.Claims;
using CacheManager.Core;
using IdentityServer4.AccessTokenValidation;
using IdentityServer4.Models;
using IdentityServer4.Test;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json; using Newtonsoft.Json;
using Ocelot.Cache; using Ocelot.Cache;
using Ocelot.Configuration.File; using Ocelot.Configuration.File;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Shouldly; using Shouldly;
using TestStack.BDDfy; using TestStack.BDDfy;
using Xunit; using Xunit;
@ -18,15 +28,16 @@ namespace Ocelot.IntegrationTests
{ {
public class AdministrationTests : IDisposable public class AdministrationTests : IDisposable
{ {
private readonly HttpClient _httpClient; private HttpClient _httpClient;
private readonly HttpClient _httpClientTwo; private readonly HttpClient _httpClientTwo;
private HttpResponseMessage _response; private HttpResponseMessage _response;
private IWebHost _builder; private IWebHost _builder;
private IWebHostBuilder _webHostBuilder; private IWebHostBuilder _webHostBuilder;
private readonly string _ocelotBaseUrl; private string _ocelotBaseUrl;
private BearerToken _token; private BearerToken _token;
private IWebHostBuilder _webHostBuilderTwo; private IWebHostBuilder _webHostBuilderTwo;
private IWebHost _builderTwo; private IWebHost _builderTwo;
private IWebHost _identityServerBuilder;
public AdministrationTests() public AdministrationTests()
{ {
@ -62,6 +73,24 @@ namespace Ocelot.IntegrationTests
.BDDfy(); .BDDfy();
} }
[Fact]
public void should_return_response_200_with_call_re_routes_controller_using_base_url_added_in_memory_with_no_webhostbuilder_registered()
{
_httpClient = new HttpClient();
_ocelotBaseUrl = "http://localhost:5011";
_httpClient.BaseAddress = new Uri(_ocelotBaseUrl);
var configuration = new FileConfiguration();
this.Given(x => GivenThereIsAConfiguration(configuration))
.And(x => GivenOcelotIsRunningWithNoWebHostBuilder(_ocelotBaseUrl))
.And(x => GivenIHaveAnOcelotToken("/administration"))
.And(x => GivenIHaveAddedATokenToMyRequest())
.When(x => WhenIGetUrlOnTheApiGateway("/administration/configuration"))
.Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
.BDDfy();
}
[Fact] [Fact]
public void should_be_able_to_use_token_from_ocelot_a_on_ocelot_b() public void should_be_able_to_use_token_from_ocelot_a_on_ocelot_b()
{ {
@ -304,6 +333,115 @@ namespace Ocelot.IntegrationTests
.BDDfy(); .BDDfy();
} }
[Fact]
public void should_return_response_200_with_call_re_routes_controller_when_using_own_identity_server_to_secure_admin_area()
{
var configuration = new FileConfiguration();
var identityServerRootUrl = "http://localhost:5123";
Action<IdentityServerAuthenticationOptions> options = o => {
o.Authority = identityServerRootUrl;
o.ApiName = "api";
o.RequireHttpsMetadata = false;
o.SupportedTokens = SupportedTokens.Both;
o.ApiSecret = "secret";
};
this.Given(x => GivenThereIsAConfiguration(configuration))
.And(x => GivenThereIsAnIdentityServerOn(identityServerRootUrl, "api"))
.And(x => GivenOcelotIsRunningWithIdentityServerSettings(options))
.And(x => GivenIHaveAToken(identityServerRootUrl))
.And(x => GivenIHaveAddedATokenToMyRequest())
.When(x => WhenIGetUrlOnTheApiGateway("/administration/configuration"))
.Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
.BDDfy();
}
private void GivenIHaveAToken(string url)
{
var formData = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("client_id", "api"),
new KeyValuePair<string, string>("client_secret", "secret"),
new KeyValuePair<string, string>("scope", "api"),
new KeyValuePair<string, string>("username", "test"),
new KeyValuePair<string, string>("password", "test"),
new KeyValuePair<string, string>("grant_type", "password")
};
var content = new FormUrlEncodedContent(formData);
using (var httpClient = new HttpClient())
{
var response = httpClient.PostAsync($"{url}/connect/token", content).Result;
var responseContent = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
_token = JsonConvert.DeserializeObject<BearerToken>(responseContent);
}
}
private void GivenThereIsAnIdentityServerOn(string url, string apiName)
{
_identityServerBuilder = new WebHostBuilder()
.UseUrls(url)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureServices(services =>
{
services.AddLogging();
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(new List<ApiResource>
{
new ApiResource
{
Name = apiName,
Description = apiName,
Enabled = true,
DisplayName = apiName,
Scopes = new List<Scope>()
{
new Scope(apiName)
}
}
})
.AddInMemoryClients(new List<Client>
{
new Client
{
ClientId = apiName,
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
ClientSecrets = new List<Secret> {new Secret("secret".Sha256())},
AllowedScopes = new List<string> { apiName },
AccessTokenType = AccessTokenType.Jwt,
Enabled = true
}
})
.AddTestUsers(new List<TestUser>
{
new TestUser
{
Username = "test",
Password = "test",
SubjectId = "1231231"
}
});
})
.Configure(app =>
{
app.UseIdentityServer();
})
.Build();
_identityServerBuilder.Start();
using (var httpClient = new HttpClient())
{
var response = httpClient.GetAsync($"{url}/.well-known/openid-configuration").Result;
response.EnsureSuccessStatusCode();
}
}
private void GivenAnotherOcelotIsRunning(string baseUrl) private void GivenAnotherOcelotIsRunning(string baseUrl)
{ {
_httpClientTwo.BaseAddress = new Uri(baseUrl); _httpClientTwo.BaseAddress = new Uri(baseUrl);
@ -312,10 +450,36 @@ namespace Ocelot.IntegrationTests
.UseUrls(baseUrl) .UseUrls(baseUrl)
.UseKestrel() .UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory()) .UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureServices(x => { .ConfigureAppConfiguration((hostingContext, config) =>
x.AddSingleton(_webHostBuilderTwo); {
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
config.AddJsonFile("configuration.json");
config.AddOcelotBaseUrl(baseUrl);
config.AddEnvironmentVariables();
}) })
.UseStartup<IntegrationTestsStartup>(); .ConfigureServices(x =>
{
Action<ConfigurationBuilderCachePart> settings = (s) =>
{
s.WithMicrosoftLogging(log =>
{
log.AddConsole(LogLevel.Debug);
})
.WithDictionaryHandle();
};
x.AddOcelot()
.AddCacheManager(settings)
.AddAdministration("/administration", "secret");
})
.Configure(app =>
{
app.UseOcelot().Wait();
});
_builderTwo = _webHostBuilderTwo.Build(); _builderTwo = _webHostBuilderTwo.Build();
@ -400,18 +564,110 @@ namespace Ocelot.IntegrationTests
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
} }
private void GivenOcelotIsRunningWithIdentityServerSettings(Action<IdentityServerAuthenticationOptions> configOptions)
{
_webHostBuilder = new WebHostBuilder()
.UseUrls(_ocelotBaseUrl)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
config.AddJsonFile("configuration.json");
config.AddEnvironmentVariables();
})
.ConfigureServices(x => {
x.AddSingleton(_webHostBuilder);
x.AddOcelot()
.AddCacheManager(c =>
{
c.WithDictionaryHandle();
})
.AddAdministration("/administration", configOptions);
})
.Configure(app => {
app.UseOcelot().Wait();
});
_builder = _webHostBuilder.Build();
_builder.Start();
}
private void GivenOcelotIsRunning() private void GivenOcelotIsRunning()
{ {
_webHostBuilder = new WebHostBuilder() _webHostBuilder = new WebHostBuilder()
.UseUrls(_ocelotBaseUrl) .UseUrls(_ocelotBaseUrl)
.UseKestrel() .UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory()) .UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
config.AddJsonFile("configuration.json");
config.AddOcelotBaseUrl(_ocelotBaseUrl);
config.AddEnvironmentVariables();
})
.ConfigureServices(x =>
{
Action<ConfigurationBuilderCachePart> settings = (s) =>
{
s.WithMicrosoftLogging(log =>
{
log.AddConsole(LogLevel.Debug);
})
.WithDictionaryHandle();
};
x.AddOcelot()
.AddCacheManager(settings)
.AddAdministration("/administration", "secret");
})
.Configure(app =>
{
app.UseOcelot().Wait();
});
_builder = _webHostBuilder.Build();
_builder.Start();
}
private void GivenOcelotIsRunningWithNoWebHostBuilder(string baseUrl)
{
_webHostBuilder = new WebHostBuilder()
.UseUrls(_ocelotBaseUrl)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
config.AddJsonFile("configuration.json");
config.AddOcelotBaseUrl(baseUrl);
config.AddEnvironmentVariables();
})
.ConfigureServices(x => { .ConfigureServices(x => {
x.AddSingleton(_webHostBuilder); x.AddSingleton(_webHostBuilder);
x.AddOcelot()
.AddCacheManager(c =>
{
c.WithDictionaryHandle();
})
.AddAdministration("/administration", "secret");
}) })
.UseStartup<IntegrationTestsStartup>(); .Configure(app => {
app.UseOcelot().Wait();
});
_builder = _webHostBuilder.Build(); _builder = _webHostBuilder.Build();
_builder.Start(); _builder.Start();
} }
@ -464,6 +720,7 @@ namespace Ocelot.IntegrationTests
Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE_PASSWORD", ""); Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE_PASSWORD", "");
_builder?.Dispose(); _builder?.Dispose();
_httpClient?.Dispose(); _httpClient?.Dispose();
_identityServerBuilder?.Dispose();
} }
} }
} }

View File

@ -1,51 +0,0 @@
using System;
using CacheManager.Core;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using ConfigurationBuilder = Microsoft.Extensions.Configuration.ConfigurationBuilder;
namespace Ocelot.IntegrationTests
{
public class IntegrationTestsStartup
{
public IntegrationTestsStartup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddJsonFile("configuration.json")
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
Action<ConfigurationBuilderCachePart> settings = (x) =>
{
x.WithMicrosoftLogging(log =>
{
log.AddConsole(LogLevel.Debug);
})
.WithDictionaryHandle();
};
services.AddOcelot(Configuration)
.AddCacheManager(settings)
.AddAdministration("/administration", "secret");
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseOcelot().Wait();
}
}
}

View File

@ -1,53 +0,0 @@
using System;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Ocelot.Raft;
using Rafty.Concensus;
using Rafty.FiniteStateMachine;
using Rafty.Infrastructure;
using Rafty.Log;
using ConfigurationBuilder = Microsoft.Extensions.Configuration.ConfigurationBuilder;
namespace Ocelot.IntegrationTests
{
public class RaftStartup
{
public RaftStartup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddJsonFile("peers.json", optional: true, reloadOnChange: true)
.AddJsonFile("configuration.json")
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
public virtual void ConfigureServices(IServiceCollection services)
{
services
.AddOcelot(Configuration)
.AddAdministration("/administration", "secret")
.AddRafty()
;
}
public virtual void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseOcelot().Wait();
}
}
}

View File

@ -17,6 +17,9 @@ using Shouldly;
using Xunit; using Xunit;
using static Rafty.Infrastructure.Wait; using static Rafty.Infrastructure.Wait;
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using Microsoft.Extensions.Configuration;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
namespace Ocelot.IntegrationTests namespace Ocelot.IntegrationTests
{ {
@ -28,7 +31,6 @@ namespace Ocelot.IntegrationTests
private FilePeers _peers; private FilePeers _peers;
private readonly HttpClient _httpClient; private readonly HttpClient _httpClient;
private readonly HttpClient _httpClientForAssertions; private readonly HttpClient _httpClientForAssertions;
private string _ocelotBaseUrl;
private BearerToken _token; private BearerToken _token;
private HttpResponseMessage _response; private HttpResponseMessage _response;
private static readonly object _lock = new object(); private static readonly object _lock = new object();
@ -37,8 +39,8 @@ namespace Ocelot.IntegrationTests
{ {
_httpClientForAssertions = new HttpClient(); _httpClientForAssertions = new HttpClient();
_httpClient = new HttpClient(); _httpClient = new HttpClient();
_ocelotBaseUrl = "http://localhost:5000"; var ocelotBaseUrl = "http://localhost:5000";
_httpClient.BaseAddress = new Uri(_ocelotBaseUrl); _httpClient.BaseAddress = new Uri(ocelotBaseUrl);
_webHostBuilders = new List<IWebHostBuilder>(); _webHostBuilders = new List<IWebHostBuilder>();
_builders = new List<IWebHost>(); _builders = new List<IWebHost>();
_threads = new List<Thread>(); _threads = new List<Thread>();
@ -331,12 +333,29 @@ namespace Ocelot.IntegrationTests
webHostBuilder.UseUrls(url) webHostBuilder.UseUrls(url)
.UseKestrel() .UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory()) .UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
config.AddJsonFile("configuration.json");
config.AddJsonFile("peers.json", optional: true, reloadOnChange: true);
config.AddOcelotBaseUrl(url);
config.AddEnvironmentVariables();
})
.ConfigureServices(x => .ConfigureServices(x =>
{ {
x.AddSingleton(webHostBuilder);
x.AddSingleton(new NodeId(url)); x.AddSingleton(new NodeId(url));
x
.AddOcelot()
.AddAdministration("/administration", "secret")
.AddRafty();
}) })
.UseStartup<RaftStartup>(); .Configure(app =>
{
app.UseOcelot().Wait();
});
var builder = webHostBuilder.Build(); var builder = webHostBuilder.Build();
builder.Start(); builder.Start();

View File

@ -13,6 +13,11 @@ using Xunit;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using CacheManager.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
namespace Ocelot.IntegrationTests namespace Ocelot.IntegrationTests
{ {
@ -97,11 +102,35 @@ namespace Ocelot.IntegrationTests
.UseUrls(_ocelotBaseUrl) .UseUrls(_ocelotBaseUrl)
.UseKestrel() .UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory()) .UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
config.AddJsonFile("configuration.json");
config.AddOcelotBaseUrl(_ocelotBaseUrl);
config.AddEnvironmentVariables();
})
.ConfigureServices(x => .ConfigureServices(x =>
{ {
x.AddSingleton(_webHostBuilder); Action<ConfigurationBuilderCachePart> settings = (s) =>
{
s.WithMicrosoftLogging(log =>
{
log.AddConsole(LogLevel.Debug);
})
.WithDictionaryHandle();
};
x.AddOcelot()
.AddCacheManager(settings)
.AddAdministration("/administration", "secret");
}) })
.UseStartup<IntegrationTestsStartup>(); .Configure(app =>
{
app.UseOcelot().Wait();
});
_builder = _webHostBuilder.Build(); _builder = _webHostBuilder.Build();

View File

@ -1,37 +0,0 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
namespace Ocelot.ManualTest
{
public class ManualTestStartup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication()
.AddJwtBearer("TestKey", x =>
{
x.Authority = "test";
x.Audience = "test";
});
services.AddOcelot()
.AddCacheManager(x =>
{
x.WithDictionaryHandle();
})
.AddOpenTracing(option =>
{
option.CollectorUrl = "http://localhost:9618";
option.Service = "Ocelot.ManualTest";
})
.AddAdministration("/administration", "secret");
}
public void Configure(IApplicationBuilder app)
{
app.UseOcelot().Wait();
}
}
}

View File

@ -3,6 +3,8 @@ using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
namespace Ocelot.ManualTest namespace Ocelot.ManualTest
{ {
@ -10,20 +12,39 @@ namespace Ocelot.ManualTest
{ {
public static void Main(string[] args) public static void Main(string[] args)
{ {
IWebHostBuilder builder = new WebHostBuilder(); new WebHostBuilder()
builder.ConfigureServices(s => { .UseKestrel()
s.AddSingleton(builder);
});
builder.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory()) .UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) => .ConfigureAppConfiguration((hostingContext, config) =>
{ {
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath); config
var env = hostingContext.HostingEnvironment; .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
config.AddJsonFile("configuration.json"); .AddJsonFile("configuration.json")
config.AddEnvironmentVariables(); .AddEnvironmentVariables()
.AddOcelotBaseUrl("http://localhost:5000");
})
.ConfigureServices(s => {
s.AddAuthentication()
.AddJwtBearer("TestKey", x =>
{
x.Authority = "test";
x.Audience = "test";
});
s.AddOcelot()
.AddCacheManager(x =>
{
x.WithDictionaryHandle();
})
.AddOpenTracing(option =>
{
option.CollectorUrl = "http://localhost:9618";
option.Service = "Ocelot.ManualTest";
})
.AddAdministration("/administration", "secret");
}) })
.ConfigureLogging((hostingContext, logging) => .ConfigureLogging((hostingContext, logging) =>
{ {
@ -31,9 +52,12 @@ namespace Ocelot.ManualTest
logging.AddConsole(); logging.AddConsole();
}) })
.UseIISIntegration() .UseIISIntegration()
.UseStartup<ManualTestStartup>(); .Configure(app =>
var host = builder.Build(); {
host.Run(); app.UseOcelot().Wait();
})
.Build()
.Run();
} }
} }
} }

View File

@ -0,0 +1,41 @@
using Microsoft.Extensions.Configuration;
using Ocelot.DependencyInjection;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.DependencyInjection
{
public class ConfigurationBuilderExtensionsTests
{
private IConfigurationRoot _configuration;
private string _result;
[Fact]
public void should_add_base_url_to_config()
{
this.Given(x => GivenTheBaseUrl("test"))
.When(x => WhenIGet("BaseUrl"))
.Then(x => ThenTheResultIs("test"))
.BDDfy();
}
private void GivenTheBaseUrl(string baseUrl)
{
var builder = new ConfigurationBuilder()
.AddOcelotBaseUrl(baseUrl);
_configuration = builder.Build();
}
private void WhenIGet(string key)
{
_result = _configuration.GetValue("BaseUrl", "");
}
private void ThenTheResultIs(string expected)
{
_result.ShouldBe(expected);
}
}
}

View File

@ -16,6 +16,7 @@ using Ocelot.Requester;
using Ocelot.UnitTests.Requester; using Ocelot.UnitTests.Requester;
using Shouldly; using Shouldly;
using System; using System;
using IdentityServer4.AccessTokenValidation;
using TestStack.BDDfy; using TestStack.BDDfy;
using Xunit; using Xunit;
@ -31,13 +32,11 @@ namespace Ocelot.UnitTests.DependencyInjection
public OcelotBuilderTests() public OcelotBuilderTests()
{ {
IWebHostBuilder builder = new WebHostBuilder(); _configRoot = new ConfigurationRoot(new List<IConfigurationProvider>());
_configRoot = new ConfigurationRoot(new List<IConfigurationProvider>()); _services = new ServiceCollection();
_services = new ServiceCollection(); _services.AddSingleton<IHostingEnvironment, HostingEnvironment>();
_services.AddSingleton(builder); _services.AddSingleton<IConfiguration>(_configRoot);
_services.AddSingleton<IHostingEnvironment, HostingEnvironment>(); _maxRetries = 100;
_services.AddSingleton<IConfiguration>(_configRoot);
_maxRetries = 100;
} }
private Exception _ex; private Exception _ex;
@ -100,6 +99,40 @@ namespace Ocelot.UnitTests.DependencyInjection
.BDDfy(); .BDDfy();
} }
[Fact]
public void should_set_up_administration_with_identity_server_options()
{
Action<IdentityServerAuthenticationOptions> options = o => {
};
this.Given(x => WhenISetUpOcelotServices())
.When(x => WhenISetUpAdministration(options))
.Then(x => ThenAnExceptionIsntThrown())
.Then(x => ThenTheCorrectAdminPathIsRegitered())
.BDDfy();
}
[Fact]
public void should_set_up_administration()
{
this.Given(x => WhenISetUpOcelotServices())
.When(x => WhenISetUpAdministration())
.Then(x => ThenAnExceptionIsntThrown())
.Then(x => ThenTheCorrectAdminPathIsRegitered())
.BDDfy();
}
private void WhenISetUpAdministration()
{
_ocelotBuilder.AddAdministration("/administration", "secret");
}
private void WhenISetUpAdministration(Action<IdentityServerAuthenticationOptions> options)
{
_ocelotBuilder.AddAdministration("/administration", options);
}
[Fact] [Fact]
public void should_use_logger_factory() public void should_use_logger_factory()
{ {
@ -255,6 +288,7 @@ namespace Ocelot.UnitTests.DependencyInjection
{ {
try try
{ {
_serviceProvider = _services.BuildServiceProvider();
var logger = _serviceProvider.GetService<IFileConfigurationSetter>(); var logger = _serviceProvider.GetService<IFileConfigurationSetter>();
} }
catch (Exception e) catch (Exception e)

View File

@ -15,6 +15,7 @@ namespace Ocelot.UnitTests.Errors
using Moq; using Moq;
using Ocelot.Configuration; using Ocelot.Configuration;
using Rafty.Concensus; using Rafty.Concensus;
using Ocelot.Errors;
public class ExceptionHandlerMiddlewareTests : ServerHostedMiddlewareTest public class ExceptionHandlerMiddlewareTests : ServerHostedMiddlewareTest
{ {
@ -40,11 +41,6 @@ namespace Ocelot.UnitTests.Errors
.BDDfy(); .BDDfy();
} }
private void TheRequestIdIsNotSet()
{
ScopedRepository.Verify(x => x.Add<string>(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[Fact] [Fact]
public void DownstreamException() public void DownstreamException()
{ {
@ -83,6 +79,55 @@ namespace Ocelot.UnitTests.Errors
.BDDfy(); .BDDfy();
} }
[Fact]
public void should_throw_exception_if_config_provider_returns_error()
{
this.Given(_ => GivenAnExceptionWillNotBeThrownDownstream())
.And(_ => GivenTheConfigReturnsError())
.When(_ => WhenICallTheMiddlewareWithTheRequestIdKey("requestidkey", "1234"))
.Then(_ => ThenAnExceptionIsThrown())
.BDDfy();
}
[Fact]
public void should_throw_exception_if_config_provider_throws()
{
this.Given(_ => GivenAnExceptionWillNotBeThrownDownstream())
.And(_ => GivenTheConfigThrows())
.When(_ => WhenICallTheMiddlewareWithTheRequestIdKey("requestidkey", "1234"))
.Then(_ => ThenAnExceptionIsThrown())
.BDDfy();
}
private void GivenTheConfigThrows()
{
var ex = new Exception("outer", new Exception("inner"));
_provider
.Setup(x => x.Get()).ThrowsAsync(ex);
}
private void ThenAnExceptionIsThrown()
{
ResponseMessage.StatusCode.ShouldBe(HttpStatusCode.InternalServerError);
}
private void GivenTheConfigReturnsError()
{
var config = new OcelotConfiguration(null, null, null, null);
var response = new Ocelot.Responses.ErrorResponse<IOcelotConfiguration>(new FakeError());
_provider
.Setup(x => x.Get()).ReturnsAsync(response);
}
public class FakeError : Error
{
public FakeError()
: base("meh", OcelotErrorCode.CannotAddDataError)
{
}
}
private void TheRequestIdIsSet(string key, string value) private void TheRequestIdIsSet(string key, string value)
{ {
ScopedRepository.Verify(x => x.Add<string>(key, value), Times.Once); ScopedRepository.Verify(x => x.Add<string>(key, value), Times.Once);
@ -140,5 +185,10 @@ namespace Ocelot.UnitTests.Errors
{ {
ResponseMessage.StatusCode.ShouldBe(HttpStatusCode.InternalServerError); ResponseMessage.StatusCode.ShouldBe(HttpStatusCode.InternalServerError);
} }
private void TheRequestIdIsNotSet()
{
ScopedRepository.Verify(x => x.Add<string>(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
} }
} }

View File

@ -3,6 +3,8 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Memory;
using Moq; using Moq;
using Ocelot.Middleware; using Ocelot.Middleware;
using Shouldly; using Shouldly;
@ -14,38 +16,41 @@ namespace Ocelot.UnitTests.Middleware
public class BaseUrlFinderTests public class BaseUrlFinderTests
{ {
private readonly BaseUrlFinder _baseUrlFinder; private readonly BaseUrlFinder _baseUrlFinder;
private readonly Mock<IWebHostBuilder> _webHostBuilder; private readonly Mock<IConfiguration> _config;
private string _result; private string _result;
public BaseUrlFinderTests() public BaseUrlFinderTests()
{ {
_webHostBuilder = new Mock<IWebHostBuilder>(); _config = new Mock<IConfiguration>();
_baseUrlFinder = new BaseUrlFinder(_webHostBuilder.Object); _baseUrlFinder = new BaseUrlFinder(_config.Object);
}
[Fact]
public void should_find_base_url_based_on_webhostbuilder()
{
this.Given(x => GivenTheWebHostBuilderReturns("http://localhost:7000"))
.When(x => WhenIFindTheUrl())
.Then(x => ThenTheUrlIs("http://localhost:7000"))
.BDDfy();
} }
[Fact] [Fact]
public void should_use_default_base_url() public void should_use_default_base_url()
{ {
this.Given(x => GivenTheWebHostBuilderReturns("")) this.Given(x => GivenTheConfigBaseUrlIs(""))
.And(x => GivenTheConfigBaseUrlIs(""))
.When(x => WhenIFindTheUrl()) .When(x => WhenIFindTheUrl())
.Then(x => ThenTheUrlIs("http://localhost:5000")) .Then(x => ThenTheUrlIs("http://localhost:5000"))
.BDDfy(); .BDDfy();
} }
private void GivenTheWebHostBuilderReturns(string url) [Fact]
public void should_use_file_config_base_url()
{ {
_webHostBuilder this.Given(x => GivenTheConfigBaseUrlIs("http://localhost:7000"))
.Setup(x => x.GetSetting(WebHostDefaults.ServerUrlsKey)) .And(x => GivenTheConfigBaseUrlIs("http://baseurlfromconfig.com:5181"))
.Returns(url); .When(x => WhenIFindTheUrl())
.Then(x => ThenTheUrlIs("http://baseurlfromconfig.com:5181"))
.BDDfy();
}
private void GivenTheConfigBaseUrlIs(string configValue)
{
var configSection = new ConfigurationSection(new ConfigurationRoot(new List<IConfigurationProvider>{new MemoryConfigurationProvider(new MemoryConfigurationSource())}), "");
configSection.Value = configValue;
_config.Setup(x => x.GetSection(It.IsAny<string>())).Returns(configSection);
} }
private void WhenIFindTheUrl() private void WhenIFindTheUrl()