Added tests for identity server reference tokens, general refactoring and come config validation

This commit is contained in:
TomPallister
2016-10-16 20:28:23 +01:00
parent 7289cd803b
commit ce84ad4fc2
26 changed files with 565 additions and 150 deletions

View File

@ -1,6 +1,8 @@
using IdentityServer4.AccessTokenValidation;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Ocelot.Library.Infrastructure.Responses;
using AuthenticationOptions = Ocelot.Library.Infrastructure.Configuration.AuthenticationOptions;
namespace Ocelot.Library.Infrastructure.Authentication
{
@ -9,17 +11,18 @@ namespace Ocelot.Library.Infrastructure.Authentication
/// </summary>
public class AuthenticationHandlerCreator : IAuthenticationHandlerCreator
{
public Response<RequestDelegate> CreateIdentityServerAuthenticationHandler(IApplicationBuilder app)
public Response<RequestDelegate> CreateIdentityServerAuthenticationHandler(IApplicationBuilder app, AuthenticationOptions authOptions)
{
var builder = app.New();
builder.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
//todo sort these options out
Authority = "http://localhost:51888",
ScopeName = "api",
RequireHttpsMetadata = false
Authority = authOptions.ProviderRootUrl,
ScopeName = authOptions.ScopeName,
RequireHttpsMetadata = authOptions.RequireHttps,
AdditionalScopes = authOptions.AdditionalScopes,
SupportedTokens = SupportedTokens.Both,
ScopeSecret = authOptions.ScopeSecret
});
builder.UseMvc();

View File

@ -2,6 +2,7 @@ using System.Collections.Generic;
using Microsoft.AspNetCore.Builder;
using Ocelot.Library.Infrastructure.Errors;
using Ocelot.Library.Infrastructure.Responses;
using AuthenticationOptions = Ocelot.Library.Infrastructure.Configuration.AuthenticationOptions;
namespace Ocelot.Library.Infrastructure.Authentication
{
@ -14,18 +15,18 @@ namespace Ocelot.Library.Infrastructure.Authentication
_creator = creator;
}
public Response<AuthenticationHandler> Get(string provider, IApplicationBuilder app)
public Response<AuthenticationHandler> Get(IApplicationBuilder app, AuthenticationOptions authOptions)
{
var handler = _creator.CreateIdentityServerAuthenticationHandler(app);
var handler = _creator.CreateIdentityServerAuthenticationHandler(app, authOptions);
if (!handler.IsError)
{
return new OkResponse<AuthenticationHandler>(new AuthenticationHandler(provider, handler.Data));
return new OkResponse<AuthenticationHandler>(new AuthenticationHandler(authOptions.Provider, handler.Data));
}
return new ErrorResponse<AuthenticationHandler>(new List<Error>
{
new UnableToCreateAuthenticationHandlerError($"Unable to create authentication handler for {provider}")
new UnableToCreateAuthenticationHandlerError($"Unable to create authentication handler for {authOptions.Provider}")
});
}
}

View File

@ -1,11 +1,12 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Ocelot.Library.Infrastructure.Responses;
using AuthenticationOptions = Ocelot.Library.Infrastructure.Configuration.AuthenticationOptions;
namespace Ocelot.Library.Infrastructure.Authentication
{
public interface IAuthenticationHandlerCreator
{
Response<RequestDelegate> CreateIdentityServerAuthenticationHandler(IApplicationBuilder app);
Response<RequestDelegate> CreateIdentityServerAuthenticationHandler(IApplicationBuilder app, AuthenticationOptions authOptions);
}
}

View File

@ -1,10 +1,11 @@
using Microsoft.AspNetCore.Builder;
using Ocelot.Library.Infrastructure.Responses;
using AuthenticationOptions = Ocelot.Library.Infrastructure.Configuration.AuthenticationOptions;
namespace Ocelot.Library.Infrastructure.Authentication
{
public interface IAuthenticationHandlerFactory
{
Response<AuthenticationHandler> Get(string provider, IApplicationBuilder app);
Response<AuthenticationHandler> Get(IApplicationBuilder app, AuthenticationOptions authOptions);
}
}

View File

@ -0,0 +1,7 @@
namespace Ocelot.Library.Infrastructure.Authentication
{
public enum SupportAuthenticationProviders
{
IdentityServer
}
}

View File

@ -1,4 +1,6 @@
namespace Ocelot.Library.Infrastructure.Builder
using System.Collections.Generic;
namespace Ocelot.Library.Infrastructure.Builder
{
using Configuration;
@ -10,38 +12,84 @@
private string _upstreamHttpMethod;
private bool _isAuthenticated;
private string _authenticationProvider;
private string _authenticationProviderUrl;
private string _scopeName;
private List<string> _additionalScopes;
private bool _requireHttps;
private string _scopeSecret;
public void WithDownstreamTemplate(string input)
public ReRouteBuilder()
{
_additionalScopes = new List<string>();
}
public ReRouteBuilder WithDownstreamTemplate(string input)
{
_downstreamTemplate = input;
return this;
}
public void WithUpstreamTemplate(string input)
public ReRouteBuilder WithUpstreamTemplate(string input)
{
_upstreamTemplate = input;
return this;
}
public void WithUpstreamTemplatePattern(string input)
public ReRouteBuilder WithUpstreamTemplatePattern(string input)
{
_upstreamTemplatePattern = input;
return this;
}
public void WithUpstreamHttpMethod(string input)
public ReRouteBuilder WithUpstreamHttpMethod(string input)
{
_upstreamHttpMethod = input;
return this;
}
public void WithIsAuthenticated(bool input)
public ReRouteBuilder WithIsAuthenticated(bool input)
{
_isAuthenticated = input;
return this;
}
public void WithAuthenticationProvider(string input)
public ReRouteBuilder WithAuthenticationProvider(string input)
{
_authenticationProvider = input;
return this;
}
public ReRouteBuilder WithAuthenticationProviderUrl(string input)
{
_authenticationProviderUrl = input;
return this;
}
public ReRouteBuilder WithAuthenticationProviderScopeName(string input)
{
_scopeName = input;
return this;
}
public ReRouteBuilder WithAuthenticationProviderAdditionalScopes(List<string> input)
{
_additionalScopes = input;
return this;
}
public ReRouteBuilder WithRequireHttps(bool input)
{
_requireHttps = input;
return this;
}
public ReRouteBuilder WithScopeSecret(string input)
{
_scopeSecret = input;
return this;
}
public ReRoute Build()
{
return new ReRoute(_downstreamTemplate, _upstreamTemplate, _upstreamHttpMethod, _upstreamTemplatePattern, _isAuthenticated, _authenticationProvider);
return new ReRoute(_downstreamTemplate, _upstreamTemplate, _upstreamHttpMethod, _upstreamTemplatePattern, _isAuthenticated, new AuthenticationOptions(_authenticationProvider, _authenticationProviderUrl, _scopeName, _requireHttps, _additionalScopes, _scopeSecret));
}
}
}

View File

@ -0,0 +1,25 @@
using System.Collections.Generic;
namespace Ocelot.Library.Infrastructure.Configuration
{
public class AuthenticationOptions
{
public AuthenticationOptions(string provider, string providerRootUrl, string scopeName, bool requireHttps, List<string> additionalScopes, string scopeSecret)
{
Provider = provider;
ProviderRootUrl = providerRootUrl;
ScopeName = scopeName;
RequireHttps = requireHttps;
AdditionalScopes = additionalScopes;
ScopeSecret = scopeSecret;
}
public string Provider { get; private set; }
public string ProviderRootUrl { get; private set; }
public string ScopeName { get; private set; }
public string ScopeSecret { get; private set; }
public bool RequireHttps { get; private set; }
public List<string> AdditionalScopes { get; private set; }
}
}

View File

@ -7,49 +7,81 @@ namespace Ocelot.Library.Infrastructure.Configuration
public class OcelotConfiguration : IOcelotConfiguration
{
private readonly IOptions<YamlConfiguration> _options;
private readonly IConfigurationValidator _configurationValidator;
private readonly List<ReRoute> _reRoutes;
private const string RegExMatchEverything = ".*";
private const string RegExMatchEndString = "$";
public OcelotConfiguration(IOptions<YamlConfiguration> options)
public OcelotConfiguration(IOptions<YamlConfiguration> options, IConfigurationValidator configurationValidator)
{
_options = options;
_configurationValidator = configurationValidator;
_reRoutes = new List<ReRoute>();
SetReRoutes();
SetUpConfiguration();
}
private void SetReRoutes()
/// <summary>
/// This method is meant to be tempoary to convert a yaml config to an ocelot config...probably wont keep this but we will see
/// will need a refactor at some point as its crap
/// </summary>
private void SetUpConfiguration()
{
foreach(var reRoute in _options.Value.ReRoutes)
var response = _configurationValidator.IsValid(_options.Value);
if (!response.IsError && !response.Data.IsError)
{
var upstreamTemplate = reRoute.UpstreamTemplate;
var placeholders = new List<string>();
for (int i = 0; i < upstreamTemplate.Length; i++)
foreach (var reRoute in _options.Value.ReRoutes)
{
if (IsPlaceHolder(upstreamTemplate, i))
{
var postitionOfPlaceHolderClosingBracket = upstreamTemplate.IndexOf('}', i);
var difference = postitionOfPlaceHolderClosingBracket - i + 1;
var variableName = upstreamTemplate.Substring(i, difference);
placeholders.Add(variableName);
}
SetUpReRoute(reRoute);
}
foreach (var placeholder in placeholders)
{
upstreamTemplate = upstreamTemplate.Replace(placeholder, RegExMatchEverything);
}
upstreamTemplate = $"{upstreamTemplate}{RegExMatchEndString}";
var isAuthenticated = !string.IsNullOrEmpty(reRoute.Authentication);
_reRoutes.Add(new ReRoute(reRoute.DownstreamTemplate, reRoute.UpstreamTemplate, reRoute.UpstreamHttpMethod, upstreamTemplate, isAuthenticated, reRoute.Authentication));
}
}
}
private static bool IsPlaceHolder(string upstreamTemplate, int i)
private void SetUpReRoute(YamlReRoute reRoute)
{
var upstreamTemplate = reRoute.UpstreamTemplate;
var placeholders = new List<string>();
for (int i = 0; i < upstreamTemplate.Length; i++)
{
if (IsPlaceHolder(upstreamTemplate, i))
{
var postitionOfPlaceHolderClosingBracket = upstreamTemplate.IndexOf('}', i);
var difference = postitionOfPlaceHolderClosingBracket - i + 1;
var variableName = upstreamTemplate.Substring(i, difference);
placeholders.Add(variableName);
}
}
foreach (var placeholder in placeholders)
{
upstreamTemplate = upstreamTemplate.Replace(placeholder, RegExMatchEverything);
}
upstreamTemplate = $"{upstreamTemplate}{RegExMatchEndString}";
var isAuthenticated = !string.IsNullOrEmpty(reRoute.AuthenticationOptions?.Provider);
if (isAuthenticated)
{
var authOptionsForRoute = new AuthenticationOptions(reRoute.AuthenticationOptions.Provider,
reRoute.AuthenticationOptions.ProviderRootUrl, reRoute.AuthenticationOptions.ScopeName,
reRoute.AuthenticationOptions.RequireHttps, reRoute.AuthenticationOptions.AdditionalScopes,
reRoute.AuthenticationOptions.ScopeSecret);
_reRoutes.Add(new ReRoute(reRoute.DownstreamTemplate, reRoute.UpstreamTemplate,
reRoute.UpstreamHttpMethod, upstreamTemplate, isAuthenticated, authOptionsForRoute
));
}
else
{
_reRoutes.Add(new ReRoute(reRoute.DownstreamTemplate, reRoute.UpstreamTemplate, reRoute.UpstreamHttpMethod,
upstreamTemplate, isAuthenticated, null));
}
}
private bool IsPlaceHolder(string upstreamTemplate, int i)
{
return upstreamTemplate[i] == '{';
}

View File

@ -2,14 +2,14 @@
{
public class ReRoute
{
public ReRoute(string downstreamTemplate, string upstreamTemplate, string upstreamHttpMethod, string upstreamTemplatePattern, bool isAuthenticated, string authenticationProvider)
public ReRoute(string downstreamTemplate, string upstreamTemplate, string upstreamHttpMethod, string upstreamTemplatePattern, bool isAuthenticated, AuthenticationOptions authenticationOptions)
{
DownstreamTemplate = downstreamTemplate;
UpstreamTemplate = upstreamTemplate;
UpstreamHttpMethod = upstreamHttpMethod;
UpstreamTemplatePattern = upstreamTemplatePattern;
IsAuthenticated = isAuthenticated;
AuthenticationProvider = authenticationProvider;
AuthenticationOptions = authenticationOptions;
}
public string DownstreamTemplate { get; private set; }
@ -17,6 +17,6 @@
public string UpstreamTemplatePattern { get; private set; }
public string UpstreamHttpMethod { get; private set; }
public bool IsAuthenticated { get; private set; }
public string AuthenticationProvider { get; private set; }
public AuthenticationOptions AuthenticationOptions { get; private set; }
}
}

View File

@ -1,5 +1,7 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Linq;
using Ocelot.Library.Infrastructure.Authentication;
using Ocelot.Library.Infrastructure.Errors;
using Ocelot.Library.Infrastructure.Responses;
@ -8,6 +10,59 @@ namespace Ocelot.Library.Infrastructure.Configuration.Yaml
public class ConfigurationValidator : IConfigurationValidator
{
public Response<ConfigurationValidationResult> IsValid(YamlConfiguration configuration)
{
var result = CheckForDupliateReRoutes(configuration);
if (result.IsError)
{
return new OkResponse<ConfigurationValidationResult>(result);
}
result = CheckForUnsupportedAuthenticationProviders(configuration);
if (result.IsError)
{
return new OkResponse<ConfigurationValidationResult>(result);
}
return new OkResponse<ConfigurationValidationResult>(result);
}
private ConfigurationValidationResult CheckForUnsupportedAuthenticationProviders(YamlConfiguration configuration)
{
var errors = new List<Error>();
foreach (var yamlReRoute in configuration.ReRoutes)
{
var isAuthenticated = !string.IsNullOrEmpty(yamlReRoute.AuthenticationOptions?.Provider);
if (!isAuthenticated)
{
continue;
}
if (IsSupportedAuthenticationProvider(yamlReRoute.AuthenticationOptions?.Provider))
{
continue;
}
var error = new UnsupportedAuthenticationProviderError($"{yamlReRoute.AuthenticationOptions?.Provider} is unsupported authentication provider, upstream template is {yamlReRoute.UpstreamTemplate}, upstream method is {yamlReRoute.UpstreamHttpMethod}");
errors.Add(error);
}
return errors.Count > 0
? new ConfigurationValidationResult(true, errors)
: new ConfigurationValidationResult(false);
}
private bool IsSupportedAuthenticationProvider(string provider)
{
SupportAuthenticationProviders supportedProvider;
return Enum.TryParse(provider, true, out supportedProvider);
}
private ConfigurationValidationResult CheckForDupliateReRoutes(YamlConfiguration configuration)
{
var duplicateUpstreamTemplates = configuration.ReRoutes
.Select(r => r.DownstreamTemplate)
@ -18,19 +73,15 @@ namespace Ocelot.Library.Infrastructure.Configuration.Yaml
if (duplicateUpstreamTemplates.Count <= 0)
{
return new OkResponse<ConfigurationValidationResult>(new ConfigurationValidationResult(false));
}
var errors = new List<Error>();
foreach (var duplicateUpstreamTemplate in duplicateUpstreamTemplates)
{
var error = new DownstreamTemplateAlreadyUsedError(string.Format("Duplicate DownstreamTemplate: {0}",
duplicateUpstreamTemplate));
errors.Add(error);
return new ConfigurationValidationResult(false);
}
return new OkResponse<ConfigurationValidationResult>(new ConfigurationValidationResult(true, errors));
var errors = duplicateUpstreamTemplates
.Select(duplicateUpstreamTemplate => new DownstreamTemplateAlreadyUsedError(string.Format("Duplicate DownstreamTemplate: {0}", duplicateUpstreamTemplate)))
.Cast<Error>()
.ToList();
return new ConfigurationValidationResult(true, errors);
}
}
}

View File

@ -0,0 +1,12 @@
using Ocelot.Library.Infrastructure.Errors;
namespace Ocelot.Library.Infrastructure.Configuration.Yaml
{
public class UnsupportedAuthenticationProviderError : Error
{
public UnsupportedAuthenticationProviderError(string message)
: base(message, OcelotErrorCode.UnsupportedAuthenticationProviderError)
{
}
}
}

View File

@ -0,0 +1,14 @@
using System.Collections.Generic;
namespace Ocelot.Library.Infrastructure.Configuration.Yaml
{
public class YamlAuthenticationOptions
{
public string Provider { get; set; }
public string ProviderRootUrl { get; set; }
public string ScopeName { get; set; }
public bool RequireHttps { get; set; }
public List<string> AdditionalScopes { get; set; }
public string ScopeSecret { get; set; }
}
}

View File

@ -5,6 +5,6 @@
public string DownstreamTemplate { get; set; }
public string UpstreamTemplate { get; set; }
public string UpstreamHttpMethod { get; set; }
public string Authentication { get; set; }
public YamlAuthenticationOptions AuthenticationOptions { get; set; }
}
}

View File

@ -9,6 +9,7 @@
CannotAddDataError,
CannotFindDataError,
UnableToCompleteRequestError,
UnableToCreateAuthenticationHandlerError
UnableToCreateAuthenticationHandlerError,
UnsupportedAuthenticationProviderError
}
}

View File

@ -1,25 +1,18 @@
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Ocelot.Library.Infrastructure.Authentication;
using Ocelot.Library.Infrastructure.Configuration;
using Ocelot.Library.Infrastructure.DownstreamRouteFinder;
using Ocelot.Library.Infrastructure.Errors;
using Ocelot.Library.Infrastructure.Repository;
using Ocelot.Library.Infrastructure.Responses;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Ocelot.Library.Infrastructure.Authentication;
namespace Ocelot.Library.Infrastructure.Middleware
{
public class AuthenticationMiddleware : OcelotMiddleware
{
private readonly RequestDelegate _next;
private RequestDelegate _authenticationNext;
private readonly IScopedRequestDataRepository _scopedRequestDataRepository;
private readonly IApplicationBuilder _app;
private readonly IAuthenticationHandlerFactory _authHandlerFactory;
@ -46,7 +39,7 @@ namespace Ocelot.Library.Infrastructure.Middleware
if (IsAuthenticatedRoute(downstreamRoute.Data.ReRoute))
{
var authenticationNext = _authHandlerFactory.Get(downstreamRoute.Data.ReRoute.AuthenticationProvider, _app);
var authenticationNext = _authHandlerFactory.Get(_app, downstreamRoute.Data.ReRoute.AuthenticationOptions);
if (!authenticationNext.IsError)
{

View File

@ -43,11 +43,13 @@ namespace Ocelot
services.AddOptions();
services.AddMvc();
services.AddMvcCore().AddAuthorization().AddJsonFormatters();
services.AddAuthentication();
services.AddLogging();
services.Configure<YamlConfiguration>(Configuration);
services.AddAuthentication();
// Add framework services.
services.AddSingleton<IConfigurationValidator, ConfigurationValidator>();
services.AddSingleton<IOcelotConfiguration, OcelotConfiguration>();
services.AddSingleton<IUrlPathToUrlTemplateMatcher, RegExUrlMatcher>();
services.AddSingleton<ITemplateVariableNameAndValueFinder, TemplateVariableNameAndValueFinder>();