Skip to content

Commit

Permalink
Merge pull request #107 from TomPallister/feature/tokens-work-across-…
Browse files Browse the repository at this point in the history
…ocelots

Feature/tokens work across ocelots
  • Loading branch information
TomPallister authored Jun 24, 2017
2 parents bc7bfc8 + e96d661 commit 1f76260
Show file tree
Hide file tree
Showing 15 changed files with 242 additions and 9 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ ClientBin/
*.dbmdl
*.dbproj.schemaview
*.pfx
!idsrv3test.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using IdentityServer4.AccessTokenValidation;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ public static IdentityServerConfiguration GetIdentityServerConfiguration()
var username = Environment.GetEnvironmentVariable("OCELOT_USERNAME");
var hash = Environment.GetEnvironmentVariable("OCELOT_HASH");
var salt = Environment.GetEnvironmentVariable("OCELOT_SALT");
var credentialsSigningCertificateLocation = Environment.GetEnvironmentVariable("OCELOT_CERTIFICATE");
var credentialsSigningCertificatePassword = Environment.GetEnvironmentVariable("OCELOT_CERTIFICATE_PASSWORD");

return new IdentityServerConfiguration(
"admin",
Expand All @@ -28,7 +30,9 @@ public static IdentityServerConfiguration GetIdentityServerConfiguration()
new List<User>
{
new User("admin", username, hash, salt)
}
},
credentialsSigningCertificateLocation,
credentialsSigningCertificatePassword
);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,7 @@ public interface IIdentityServerConfiguration
AccessTokenType AccessTokenType {get;}
bool RequireClientSecret {get;}
List<User> Users {get;}
string CredentialsSigningCertificateLocation { get; }
string CredentialsSigningCertificatePassword { get; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public IdentityServerConfiguration(
IEnumerable<string> grantType,
AccessTokenType accessTokenType,
bool requireClientSecret,
List<User> users)
List<User> users, string credentialsSigningCertificateLocation, string credentialsSigningCertificatePassword)
{
ApiName = apiName;
RequireHttps = requireHttps;
Expand All @@ -30,6 +30,8 @@ public IdentityServerConfiguration(
AccessTokenType = accessTokenType;
RequireClientSecret = requireClientSecret;
Users = users;
CredentialsSigningCertificateLocation = credentialsSigningCertificateLocation;
CredentialsSigningCertificatePassword = credentialsSigningCertificatePassword;
}

public string ApiName { get; private set; }
Expand All @@ -43,5 +45,7 @@ public IdentityServerConfiguration(
public AccessTokenType AccessTokenType {get;private set;}
public bool RequireClientSecret {get;private set;}
public List<User> Users {get;private set;}
public string CredentialsSigningCertificateLocation { get; private set; }
public string CredentialsSigningCertificatePassword { get; private set; }
}
}
18 changes: 16 additions & 2 deletions src/Ocelot/DependencyInjection/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using Microsoft.IdentityModel.Tokens;
using Ocelot.Configuration;
using FileConfigurationProvider = Ocelot.Configuration.Provider.FileConfigurationProvider;

Expand Down Expand Up @@ -87,8 +89,10 @@ public static IServiceCollection AddOcelot(this IServiceCollection services, ICo
{
services.TryAddSingleton<IIdentityServerConfiguration>(identityServerConfiguration);
services.TryAddSingleton<IHashMatcher, HashMatcher>();
services.AddIdentityServer()
.AddTemporarySigningCredential()
var identityServerBuilder = services
.AddIdentityServer(options => {
options.IssuerUri = "Ocelot";
})
.AddInMemoryApiResources(new List<ApiResource>
{
new ApiResource
Expand Down Expand Up @@ -120,6 +124,16 @@ public static IServiceCollection AddOcelot(this IServiceCollection services, ICo
RequireClientSecret = identityServerConfiguration.RequireClientSecret
}
}).AddResourceOwnerValidator<OcelotResourceOwnerPasswordValidator>();

if (string.IsNullOrEmpty(identityServerConfiguration.CredentialsSigningCertificateLocation) || string.IsNullOrEmpty(identityServerConfiguration.CredentialsSigningCertificatePassword))
{
identityServerBuilder.AddTemporarySigningCredential();
}
else
{
var cert = new X509Certificate2(identityServerConfiguration.CredentialsSigningCertificateLocation, identityServerConfiguration.CredentialsSigningCertificatePassword);
identityServerBuilder.AddSigningCredential(cert);
}
}

var assembly = typeof(FileConfigurationController).GetTypeInfo().Assembly;
Expand Down
1 change: 0 additions & 1 deletion src/Ocelot/Middleware/OcelotMiddlewareExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,6 @@ private static async Task CreateAdministrationArea(IApplicationBuilder builder)
builder.Map(configuration.AdministrationPath, app =>
{
var identityServerUrl = $"{baseSchemeUrlAndPort}/{configuration.AdministrationPath.Remove(0,1)}";

app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = identityServerUrl,
Expand Down
2 changes: 1 addition & 1 deletion test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
</PropertyGroup>

<ItemGroup>
<None Update="configuration.json">
<None Update="configuration.json;appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
Expand Down
10 changes: 10 additions & 0 deletions test/Ocelot.AcceptanceTests/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"Logging": {
"IncludeScopes": true,
"LogLevel": {
"Default": "Error",
"System": "Error",
"Microsoft": "Error"
}
}
}
57 changes: 57 additions & 0 deletions test/Ocelot.IntegrationTests/AdministrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,19 @@ namespace Ocelot.IntegrationTests
public class AdministrationTests : IDisposable
{
private readonly HttpClient _httpClient;
private readonly HttpClient _httpClientTwo;
private HttpResponseMessage _response;
private IWebHost _builder;
private IWebHostBuilder _webHostBuilder;
private readonly string _ocelotBaseUrl;
private BearerToken _token;
private IWebHostBuilder _webHostBuilderTwo;
private IWebHost _builderTwo;

public AdministrationTests()
{
_httpClient = new HttpClient();
_httpClientTwo = new HttpClient();
_ocelotBaseUrl = "http://localhost:5000";
_httpClient.BaseAddress = new Uri(_ocelotBaseUrl);
}
Expand Down Expand Up @@ -70,6 +74,27 @@ public void should_return_response_200_with_call_re_routes_controller()
.BDDfy();
}

[Fact]
public void should_be_able_to_use_token_from_ocelot_a_on_ocelot_b()
{
var configuration = new FileConfiguration
{
GlobalConfiguration = new FileGlobalConfiguration
{
AdministrationPath = "/administration"
}
};

this.Given(x => GivenThereIsAConfiguration(configuration))
.And(x => GivenIdentityServerSigningEnvironmentalVariablesAreSet())
.And(x => GivenOcelotIsRunning())
.And(x => GivenIHaveAnOcelotToken("/administration"))
.And(x => GivenAnotherOcelotIsRunning("http://localhost:5007"))
.When(x => WhenIGetUrlOnTheSecondOcelot("/administration/configuration"))
.Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
.BDDfy();
}

[Fact]
public void should_return_file_configuration()
{
Expand Down Expand Up @@ -193,6 +218,36 @@ public void should_get_file_configuration_edit_and_post_updated_version()
.BDDfy();
}

private void GivenAnotherOcelotIsRunning(string baseUrl)
{
_httpClientTwo.BaseAddress = new Uri(baseUrl);

_webHostBuilderTwo = new WebHostBuilder()
.UseUrls(baseUrl)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureServices(x => {
x.AddSingleton(_webHostBuilderTwo);
})
.UseStartup<Startup>();

_builderTwo = _webHostBuilderTwo.Build();

_builderTwo.Start();
}

private void GivenIdentityServerSigningEnvironmentalVariablesAreSet()
{
Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE", "idsrv3test.pfx");
Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE_PASSWORD", "idsrv3test");
}

private void WhenIGetUrlOnTheSecondOcelot(string url)
{
_httpClientTwo.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token.AccessToken);
_response = _httpClientTwo.GetAsync(url).Result;
}

private void WhenIPostOnTheApiGateway(string url, FileConfiguration updatedConfiguration)
{
var json = JsonConvert.SerializeObject(updatedConfiguration);
Expand Down Expand Up @@ -305,6 +360,8 @@ private void ThenTheStatusCodeShouldBe(HttpStatusCode expectedHttpStatusCode)

public void Dispose()
{
Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE", "");
Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE_PASSWORD", "");
_builder?.Dispose();
_httpClient?.Dispose();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
</PropertyGroup>

<ItemGroup>
<None Update="configuration.json;appsettings.json">
<None Update="configuration.json;appsettings.json;idsrv3test.pfx">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
Expand Down
4 changes: 2 additions & 2 deletions test/Ocelot.IntegrationTests/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
"IncludeScopes": true,
"LogLevel": {
"Default": "Error",
"System": "Information",
"Microsoft": "Information"
"System": "Error",
"Microsoft": "Error"
}
}
}
Binary file added test/Ocelot.IntegrationTests/idsrv3test.pfx
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using Ocelot.Configuration.Creator;
using Shouldly;
using Xunit;

namespace Ocelot.UnitTests.Configuration
{
public class IdentityServerConfigurationCreatorTests
{
[Fact]
public void happy_path_only_exists_for_test_coverage_even_uncle_bob_probably_wouldnt_test_this()
{
var result = IdentityServerConfigurationCreator.GetIdentityServerConfiguration();
result.ApiName.ShouldBe("admin");
}
}
}
125 changes: 125 additions & 0 deletions test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Ocelot.DownstreamRouteFinder;
using Ocelot.DownstreamUrlCreator;
using Ocelot.DownstreamUrlCreator.UrlTemplateReplacer;
using Ocelot.Errors.Middleware;
using Ocelot.Infrastructure.RequestData;
using Ocelot.Logging;
using Ocelot.Responses;
using Ocelot.Values;
using Shouldly;
using TestStack.BDDfy;
using Xunit;

namespace Ocelot.UnitTests.Errors
{
public class ExceptionHandlerMiddlewareTests
{
private readonly Mock<IRequestScopedDataRepository> _scopedRepository;
private readonly string _url;
private TestServer _server;
private HttpClient _client;
private HttpResponseMessage _result;

public ExceptionHandlerMiddlewareTests()
{
_url = "http://localhost:52879";
_scopedRepository = new Mock<IRequestScopedDataRepository>();
}

[Fact]
public void should_call_next_middleware()
{
this.Given(_ => GivenASuccessfulRequest())
.When(_ => WhenIMakeTheRequest())
.Then(_ => ThenTheResponseIsOk())
.BDDfy();
}

[Fact]
public void should_call_return_error()
{
this.Given(_ => GivenAnError())
.When(_ => WhenIMakeTheRequest())
.Then(_ => ThenTheResponseIsError())
.BDDfy();
}

private void ThenTheResponseIsOk()
{
_result.StatusCode.ShouldBe(HttpStatusCode.OK);
}

private void ThenTheResponseIsError()
{
_result.StatusCode.ShouldBe(HttpStatusCode.InternalServerError);
}

private void WhenIMakeTheRequest()
{
_result = _client.GetAsync("/").Result;
}

private void GivenASuccessfulRequest()
{
var builder = new WebHostBuilder()
.ConfigureServices(x =>
{
x.AddSingleton<IOcelotLoggerFactory, AspDotNetLoggerFactory>();
x.AddLogging();
x.AddSingleton(_scopedRepository.Object);
})
.UseUrls(_url)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseUrls(_url)
.Configure(app =>
{
app.UseExceptionHandlerMiddleware();
app.Run(async context =>
{
context.Response.StatusCode = 200;
});
});

_server = new TestServer(builder);
_client = _server.CreateClient();
}

private void GivenAnError()
{
var builder = new WebHostBuilder()
.ConfigureServices(x =>
{
x.AddSingleton<IOcelotLoggerFactory, AspDotNetLoggerFactory>();
x.AddLogging();
x.AddSingleton(_scopedRepository.Object);
})
.UseUrls(_url)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseUrls(_url)
.Configure(app =>
{
app.UseExceptionHandlerMiddleware();
app.Use(async (context, next) =>
{
throw new Exception("BOOM");
});
});

_server = new TestServer(builder);
_client = _server.CreateClient();
}
}
}

0 comments on commit 1f76260

Please sign in to comment.