Skip to content

Commit

Permalink
Simplified integration tests (#252)
Browse files Browse the repository at this point in the history
Simplified integration tests
  • Loading branch information
skoruba authored Oct 5, 2019
2 parents d8f6d0a + a1f699e commit 3a3bdf8
Show file tree
Hide file tree
Showing 22 changed files with 196 additions and 228 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
Expand All @@ -9,60 +9,25 @@ namespace Skoruba.IdentityServer4.Admin.Middlewares
public class AuthenticatedTestRequestMiddleware
{
private readonly RequestDelegate _next;

public const string TestUserPrefixHeader = "TestUser";
public const string TestUserId = "UserId";
public const string TestUserName = "UserName";
public const string TestUserRoles = "UserRoles";
public static readonly string TestAuthorizationHeader = "FakeAuthorization";
public const string TestAdministrationRole = "SkorubaIdentityAdminAdministrator";

public AuthenticatedTestRequestMiddleware(RequestDelegate next)
{
_next = next;
}

public async Task Invoke(HttpContext context)
{
if (context.Request.Headers.Keys.Contains($"{TestUserPrefixHeader}-{TestUserName}"))
if (context.Request.Headers.Keys.Contains(TestAuthorizationHeader))
{
var name =
context.Request.Headers[$"{TestUserPrefixHeader}-{TestUserName}"].First();

var id =
context.Request.Headers.Keys.Contains($"{TestUserPrefixHeader}-{TestUserId}")
? context.Request.Headers[$"{TestUserPrefixHeader}-{TestUserId}"].First() : string.Empty;

var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, name),
new Claim(ClaimTypes.NameIdentifier, id),
};

AddRoles(context, claims);

var claimsIdentity = new ClaimsIdentity(claims, "Cookies");

var token = context.Request.Headers[TestAuthorizationHeader].Single();
var jwt = new JwtSecurityToken(token);
var claimsIdentity = new ClaimsIdentity(jwt.Claims, "Cookies");
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
context.User = claimsPrincipal;
}

await _next(context);
}

private void AddRoles(HttpContext context, List<Claim> claims)
{
var roles = context.Request.Headers.Keys.Contains($"{TestUserPrefixHeader}-{TestUserRoles}")
? context.Request.Headers[$"{TestUserPrefixHeader}-{TestUserRoles}"].First()
: string.Empty;

var rolesList = new List<string>();

if (!string.IsNullOrEmpty(roles))
{
rolesList.AddRange(roles.Split(','));
}

claims.AddRange(rolesList.Select(role => new Claim(ClaimTypes.Role, role)));
}
}
}
7 changes: 3 additions & 4 deletions src/Skoruba.IdentityServer4.Admin/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public static async Task Main(string[] args)
var seed = args.Any(x => x == SeedArgs);
if (seed) args = args.Except(new[] { SeedArgs }).ToArray();

var host = BuildWebHost(args);
var host = CreateWebHostBuilder(args).Build();

// Uncomment this to seed upon startup, alternatively pass in `dotnet run /seed` to seed using CLI
// await DbMigrationHelpers.EnsureSeedData<IdentityServerConfigurationDbContext, AdminIdentityDbContext, IdentityServerPersistedGrantDbContext, AdminLogDbContext, UserIdentity, UserIdentityRole>(host);
Expand All @@ -30,11 +30,10 @@ public static async Task Main(string[] args)
host.Run();
}

public static IWebHost BuildWebHost(string[] args) =>
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseKestrel(c => c.AddServerHeader = false)
.UseStartup<Startup>()
.UseSerilog()
.Build();
.UseSerilog();
}
}
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
using System.Net.Http;
using Skoruba.IdentityServer4.Admin.Configuration.Constants;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http;
using System.Security.Claims;
using Skoruba.IdentityServer4.Admin.Configuration.Interfaces;
using Skoruba.IdentityServer4.Admin.Middlewares;

namespace Skoruba.IdentityServer4.Admin.IntegrationTests.Common
{
public static class HttpClientExtensions
{
public static void SetAdminClaimsViaHeaders(this HttpClient client)
public static void SetAdminClaimsViaHeaders(this HttpClient client, IAdminConfiguration adminConfiguration)
{
client.DefaultRequestHeaders.Add($"{AuthenticatedTestRequestMiddleware.TestUserPrefixHeader}-{AuthenticatedTestRequestMiddleware.TestUserId}", "1");
client.DefaultRequestHeaders.Add($"{AuthenticatedTestRequestMiddleware.TestUserPrefixHeader}-{AuthenticatedTestRequestMiddleware.TestUserName}", "test");
client.DefaultRequestHeaders.Add($"{AuthenticatedTestRequestMiddleware.TestUserPrefixHeader}-{AuthenticatedTestRequestMiddleware.TestUserRoles}", AuthenticatedTestRequestMiddleware.TestAdministrationRole);
}
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.Name, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.Role, adminConfiguration.AdministrationRole)
};

var token = new JwtSecurityToken(claims: claims);
var t = new JwtSecurityTokenHandler().WriteToken(token);
client.DefaultRequestHeaders.Add(AuthenticatedTestRequestMiddleware.TestAuthorizationHeader, t);
}
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using System.Net.Http;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;

namespace Skoruba.IdentityServer4.Admin.IntegrationTests.Common
{
public static class WebApplicationFactoryExtensions
{
public static HttpClient SetupClient(this WebApplicationFactory<Startup> fixture)
{
var options = new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
};

return fixture.WithWebHostBuilder(
builder => builder
.UseEnvironment(EnvironmentName.Staging)
.ConfigureTestServices(services => { })
).CreateClient(options);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="5.5.3" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="2.2.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.9.0" />
<PackageReference Include="xunit" Version="2.4.1" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System.Net.Http;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Skoruba.IdentityServer4.Admin.Configuration.Interfaces;
using Skoruba.IdentityServer4.Admin.IntegrationTests.Common;
using Xunit;

namespace Skoruba.IdentityServer4.Admin.IntegrationTests.Tests.Base
{
public class BaseClassFixture : IClassFixture<WebApplicationFactory<Startup>>
{
protected readonly WebApplicationFactory<Startup> Factory;
protected readonly HttpClient Client;

public BaseClassFixture(WebApplicationFactory<Startup> factory)
{
Factory = factory;
Client = factory.SetupClient();
Factory.CreateClient();
}

protected virtual void SetupAdminClaimsViaHeaders()
{
using (var scope = Factory.Server.Host.Services.CreateScope())
{
var configuration = scope.ServiceProvider.GetRequiredService<IRootConfiguration>();
Client.SetAdminClaimsViaHeaders(configuration.AdminConfiguration);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,48 +2,50 @@
using System.Net.Http;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Skoruba.IdentityServer4.Admin.Configuration.Constants;
using Skoruba.IdentityServer4.Admin.Configuration.Interfaces;
using Skoruba.IdentityServer4.Admin.IntegrationTests.Common;
using Skoruba.IdentityServer4.Admin.IntegrationTests.Tests.Base;
using Xunit;

namespace Skoruba.IdentityServer4.Admin.IntegrationTests.Tests
{
public class ConfigurationControllerTests : IClassFixture<TestFixture>
public class ConfigurationControllerTests : BaseClassFixture
{
private readonly HttpClient _client;

public ConfigurationControllerTests(TestFixture fixture)
public ConfigurationControllerTests(WebApplicationFactory<Startup> factory)
: base(factory)
{
_client = fixture.Client;
}

[Fact]
public async Task ReturnSuccessWithAdminRole()
{
//Get claims for admin
_client.SetAdminClaimsViaHeaders();
SetupAdminClaimsViaHeaders();

foreach (var route in RoutesConstants.GetConfigureRoutes())
{
// Act
var response = await _client.GetAsync($"/Configuration/{route}");
var response = await Client.GetAsync($"/Configuration/{route}");

// Assert
response.EnsureSuccessStatusCode();
response.StatusCode.Should().Be(HttpStatusCode.OK);
}
}


[Fact]
public async Task ReturnRedirectWithoutAdminRole()
{
//Remove
_client.DefaultRequestHeaders.Clear();
Client.DefaultRequestHeaders.Clear();

foreach (var route in RoutesConstants.GetConfigureRoutes())
{
// Act
var response = await _client.GetAsync($"/Configuration/{route}");
var response = await Client.GetAsync($"/Configuration/{route}");

// Assert
response.StatusCode.Should().Be(HttpStatusCode.Redirect);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,32 +1,29 @@
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.AspNetCore.Mvc.Testing;
using Skoruba.IdentityServer4.Admin.Configuration.Constants;
using Skoruba.IdentityServer4.Admin.IntegrationTests.Common;
using Skoruba.IdentityServer4.Admin.IntegrationTests.Tests.Base;
using Xunit;

namespace Skoruba.IdentityServer4.Admin.IntegrationTests.Tests
{
public class GrantControllerTests : IClassFixture<TestFixture>
public class GrantControllerTests : BaseClassFixture
{
private readonly HttpClient _client;

public GrantControllerTests(TestFixture fixture)
public GrantControllerTests(WebApplicationFactory<Startup> factory) : base(factory)
{
_client = fixture.Client;
}

[Fact]
public async Task ReturnSuccessWithAdminRole()
{
//Get claims for admin
_client.SetAdminClaimsViaHeaders();
SetupAdminClaimsViaHeaders();

foreach (var route in RoutesConstants.GetGrantRoutes())
{
// Act
var response = await _client.GetAsync($"/Grant/{route}");
var response = await Client.GetAsync($"/Grant/{route}");

// Assert
response.EnsureSuccessStatusCode();
Expand All @@ -38,12 +35,12 @@ public async Task ReturnSuccessWithAdminRole()
public async Task ReturnRedirectWithoutAdminRole()
{
//Remove
_client.DefaultRequestHeaders.Clear();
Client.DefaultRequestHeaders.Clear();

foreach (var route in RoutesConstants.GetGrantRoutes())
{
// Act
var response = await _client.GetAsync($"/Grant/{route}");
var response = await Client.GetAsync($"/Grant/{route}");

// Assert
response.StatusCode.Should().Be(HttpStatusCode.Redirect);
Expand Down
Loading

0 comments on commit 3a3bdf8

Please sign in to comment.