简体   繁体   English

在 .NET Core 3.0 的集成测试中创建未经身份验证的请求

[英]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 .NET Core 2.2 有一个很好的解决方案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显然它在 .NET Core 3.0 中停止工作

Error Message: Expected response.StatusCode to be OK, but found Unauthorized.错误消息:预期 response.StatusCode 正常,但发现未授权。 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)堆栈跟踪:在 FluentAssertions.Execution.TestFrameworkProvider.Throw(String message) 在 FluentAssertions.Execution.DefaultAssertionStrategy.HandleFailure(String message) 在 FluentAssertions.Execution.AssertionScope.FailWith(Func' 的 FluentAssertions.Execution.LateBoundTestFramework.Throw(String message) 1 failReasonFunc) 在 FluentAssertions.Execution.AssertionScope.FailWith(Func'1 failReasonFunc) 在 FluentAssertions.Execution.AssertionScope.FailWith(String message, Object[] args) 在 FluentAssertions.Primitives.ObjectAssertions.Be(Object expected, String because, Object [] 因为Args)

Does anyone know if there is a similar workaround for the new .NET Core?有谁知道新的 .NET Core 是否有类似的解决方法?

I was using the same method under .NET Core 2.2.我在 .NET Core 2.2 下使用了相同的方法。 What I finally found that worked for .NET Core 3.0 is based on Integration Tests - Mock Authentication .我最终发现适用于 .NET Core 3.0 的是基于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然后在ConfigureTestServices我改变了逻辑

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.这现在允许我的测试在 .NET Core 3.0 下工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM