Create unauthenticated request in integration tests in .NET Core 3.0

Viewed 1365

There was a nice solution for .NET Core 2.2 posted here https://stackoverflow.com/a/50247041

protected override void ConfigureWebHost(IWebHostBuilder builder)
{
    builder.ConfigureTestServices(services =>
    {
        services
            .AddMvc(opts => opts.Filters.Add(new AllowAnonymousFilter()));
    });
}

Apparently it stopped working in .NET Core 3.0

Error Message: Expected response.StatusCode to be OK, but found Unauthorized. Stack Trace: at FluentAssertions.Execution.LateBoundTestFramework.Throw(String message) at FluentAssertions.Execution.TestFrameworkProvider.Throw(String message) at FluentAssertions.Execution.DefaultAssertionStrategy.HandleFailure(String message) at FluentAssertions.Execution.AssertionScope.FailWith(Func'1 failReasonFunc) at FluentAssertions.Execution.AssertionScope.FailWith(Func'1 failReasonFunc) at FluentAssertions.Execution.AssertionScope.FailWith(String message, Object[] args) at FluentAssertions.Primitives.ObjectAssertions.Be(Object expected, String because, Object[] becauseArgs)

Does anyone know if there is a similar workaround for the new .NET Core?

1 Answers

I was using the same method under .NET Core 2.2. What I finally found that worked for .NET Core 3.0 is based on Integration Tests - Mock Authentication. I added a Mock Test Auth Handler as such:

public class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    public TestAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
        : base(options, logger, encoder, clock)
    {
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var claims = new[] { new Claim(ClaimTypes.Name, "Test user") };
        var identity = new ClaimsIdentity(claims, "Test");
        var principal = new ClaimsPrincipal(identity);
        var ticket = new AuthenticationTicket(principal, "Test");

        AuthenticateResult result = AuthenticateResult.Success(ticket);

        return Task.FromResult(result);
    }
}

Then in the ConfigureTestServices I changed the logic from

services.AddControllers(options =>
    {
        options.Filters.Add(new AllowAnonymousFilter());
    });

to add an Authentication and override the Authorization Policy as such:

services
    .AddAuthentication("Test")
    .AddScheme<AuthenticationSchemeOptions, TestAuthHandler>("Test", options => { });
services.AddAuthorization(options =>
{
    options.AddPolicy("<Existing Policy Name>", builder =>
    {
        builder.AuthenticationSchemes.Add("Test");
        builder.RequireAuthenticatedUser();
    });
    options.DefaultPolicy = options.GetPolicy("<Existing Policy Name>");
});

This now allowed my tests to work under .NET Core 3.0.

Related