首页 > 解决方案 > Create unauthenticated request in integration tests in .NET Core 3.0

问题描述

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?

标签: c#asp.net-coreintegration-testingasp.net-core-3.0

解决方案


我在 .NET Core 2.2 下使用了相同的方法。我最终发现适用于 .NET Core 3.0 的是基于Integration Tests - Mock Authentication。我添加了一个模拟测试身份验证处理程序,如下所示:

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);
    }
}

然后在ConfigureTestServices我改变了逻辑

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

添加身份验证并覆盖授权策略,如下所示:

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>");
});

这现在允许我的测试在 .NET Core 3.0 下工作。


推荐阅读