Trying to implement authorization in my ASP.NET Core integration tests.
This is my TestAuthHandler
class:
internal class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
public static bool IsAuthenticated { get; set; } = true; // Default to true for authenticated state
private static Claim[] salesPersonClaims = new[] {
new Claim(ClaimTypes.NameIdentifier, "672d1a4c4ca5428f35ded85c"), // user_id
new Claim(ClaimTypes.Name, "Verkoper1"), // Name
new Claim(ClaimTypes.Email, "[email protected]"), // Email
new Claim("salesPersonId", "1"), // app_metadata.salesPersonId
new Claim(ClaimTypes.Role, "Verkoper"), // Role
};
private static Claim[] adminClaims = new[] {
new Claim(ClaimTypes.NameIdentifier, "6732640d8ddbb0b407c117b5"), // user_id
new Claim(ClaimTypes.Name, "Willy De Vrees"), // Name
new Claim(ClaimTypes.Email, "[email protected]"), // Email
new Claim(ClaimTypes.Role, "Admin"), // Role
new Claim(ClaimTypes.Role, "Verkoper"),
};
private static ClaimsIdentity identity = default!;
public TestAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder) : base(options, logger, encoder)
{
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (!IsAuthenticated)
{
return Task.FromResult(AuthenticateResult.Fail("Not authenticated"));
}
// Create a test identity with some claims
LoginSalesPerson();
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, "TestScheme");
var result = AuthenticateResult.Success(ticket);
return Task.FromResult(result);
}
public static void LoginSalesPerson()
{
identity = new ClaimsIdentity(salesPersonClaims, "TestScheme");
}
public static void LoginAdmin()
{
identity = new ClaimsIdentity(adminClaims, "TestScheme");
}
}
I expose IsAuthenticated
, LoginAdmin
and LoginSalesPerson
to the factory.
These methods can then be used by tests to perform logged out
, admin logged in
and salesperson logged in
requests
Performing logged out requests works great.
But performing authorized requests, for example a controller method with attribute:
[Authorize(Roles="Admin")]
Fails and throws a 403, while in the real app they work wonderfully.
In my fakeappfactory did I forget to override something?
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureTestServices(services =>
{
// Clear all previous db options/configuration
services.RemoveAll(typeof(DbContextOptions<ApplicationDbContext>));
var connString = GetConnectionString();
services.AddSqlServer<ApplicationDbContext>(connString);
services.AddHttpContextAccessor();
// When AUTH requests comes in Handler Class will deal with it
// Override authentication set in the Program.cs class.
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "TestScheme";
options.DefaultChallengeScheme = "TestScheme";
})
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>("TestScheme", options => { });
// Clear database for a clean start
var dbContext = CreateDbContext(services);
dbContext.Database.EnsureDeleted();
});
}
Example of a test that fails:
[Fact]
private async Task GetQuotesList_Empty_ShouldBeEmpty()
{
_application.LoginAdmin();
//Arrange
await _dbContext.Quotes.Where(q => q.Id == 1).ExecuteDeleteAsync();
//Act
var response = await _httpClient.GetAsync("api/quotes/all");
response.EnsureSuccessStatusCode();
var quotes = await response.Content.ReadFromJsonAsync<IEnumerable<QuoteListItemDTO>>();
//Assert
quotes.Any().ShouldBe(false);
}