c# - 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?
解决方案
我在 .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 下工作。
推荐阅读
- swift - 当从 GeometryReader 中进行更改时,SwiftUI 不会反映对 @Binding @State 变量的更改
- python-3.x - 查找 numpy 数组上的所有最大值
- javascript - Foreach 在 foreach 中,同时附加到结果 div
- html - 如何从文本中删除两个重复项(原始和重复)?
- arduino - 在 Arduino 上通过 MQTT 将 int 数组发布为字符串
- python-3.x - 用每个 SD 的数据百分比或计数绘制正态分布
- java - 尝试使用 JAVA 读取 Scroll Lock 状态
- ruby - 另一个变量中的 Ruby 变量替换
- vue.js - Chart.js - 样式图例 - 每行一个图例条目
- azure-application-insights - ApplicationInsights - 通过 REST 创建规则