ASP.NET Core integration testing authorization issue

I am trying to implement authorization in my ASP.NET Core integration tests.

This is my TestAuthHandler:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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");
}
}
</code>
<code>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"); } } </code>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>[Authorize(Roles="Admin")]
</code>
<code>[Authorize(Roles="Admin")] </code>
[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?

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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();
});
}
</code>
<code>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(); }); } </code>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>[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);
}
</code>
<code>[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); } </code>
[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);
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật