ASP.NET Core 3 mock authorization during integration testing
Solution 1:
Have a related problem and have stumbled on this article here
it shows that you can override the user that is set in the HttpContext this way:
class FakeUserFilter : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
context.HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity(new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, "123"),
new Claim(ClaimTypes.Name, "Test user"),
new Claim(ClaimTypes.Email, "[email protected]"),
new Claim(ClaimTypes.Role, "Admin")
}));
await next();
}
}
and then inject it in ConfigureTestServices:
builder.ConfigureTestServices(services =>
{
services.AddMvc(options =>
{
options.Filters.Add(new AllowAnonymousFilter());
options.Filters.Add(new FakeUserFilter());
})
.AddApplicationPart(typeof(Startup).Assembly);
});
Hope this helps
Solution 2:
Check out this documentation https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1 at "Mock Authentication" session. I think that you need to add this code after create you client:
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Test");