-
Notifications
You must be signed in to change notification settings - Fork 10.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Cannot override authentication in Microsoft.AspNetCore.Mvc.Testing #45608
Comments
To verify that other service can be overridden I also added a IWeatherService which gets replaced from the same ConfigureTestServices and that does work, so not sure what the difference is here :) |
Triage: We need to investigate if the authentication options changes that we made in .NET 7 might have had a downstream impact on the testing overrides that happen here. |
To learn more about what this message means, what to expect next, and how this issue will be handled you can read our Triage Process document. |
Not sure if the issue is just .net7 and newer, it also appears to be present in net6.0 Perhaps I missed something in the guide, or perhaps just like the linked issue regarding config the order of loading the testserver/normal app changed |
I am a step further in troubleshooting thanks to a comment on https://mazeez.dev/posts/auth-in-integration-tests public class WebApp : WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureTestServices(services =>
{
// works
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = TestAuthHandler.AuthenticationScheme;
options.DefaultScheme = TestAuthHandler.AuthenticationScheme;
options.DefaultChallengeScheme = TestAuthHandler.AuthenticationScheme;
})
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(TestAuthHandler.AuthenticationScheme, options => {});
// does not work
services.AddAuthentication(defaultScheme: TestAuthHandler.AuthenticationScheme)
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(TestAuthHandler.AuthenticationScheme, options => { });
});
}
} Which means I can test authentication now. var factory = new WebApp();
var client = factory.CreateDefaultClient();
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(scheme: TestAuthHandler.AuthenticationScheme); As I understand it the AuthenticationHeaderValue is what should have triggered TestAuthHandler |
I have the exact same issue, hope there will be some updates on this. |
Has anyone looked into this recently? It's a big roadblock for me. |
same problem over here... |
I think I have a workaround for the issue. Description: As you can see here, Workaround:
public class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>, IAuthenticationRequestHandler
{
public TestAuthHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock)
: base(options, logger, encoder, clock)
{
}
public async Task<bool> HandleRequestAsync()
{
if (Request.Headers.Authorization != "TestScheme")
return false;
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, "TestScheme");
var authFeatures = new AuthenticationFeatures(AuthenticateResult.Success(ticket));
Context.Features.Set<IHttpAuthenticationFeature>(authFeatures);
Context.Features.Set<IAuthenticateResultFeature>(authFeatures);
// return false, otherwise the AuthenticationMiddleware will finish the pipeline
return false;
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
// this should never be called
throw new NotImplementedException();
}
/// <summary>
/// Copied from https://github.com/dotnet/aspnetcore/blob/main/src/Security/Authentication/Core/src/AuthenticationFeatures.cs
/// </summary>
internal sealed class AuthenticationFeatures : IAuthenticateResultFeature, IHttpAuthenticationFeature
{
private ClaimsPrincipal? _user;
private AuthenticateResult? _result;
public AuthenticationFeatures(AuthenticateResult result)
{
AuthenticateResult = result;
}
public AuthenticateResult? AuthenticateResult
{
get => _result;
set
{
_result = value;
_user = _result?.Principal;
}
}
public ClaimsPrincipal? User
{
get => _user;
set
{
_user = value;
_result = null;
}
}
}
}
builder.ConfigureTestServices(services =>
{
services.AddAuthentication()
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(
"TestScheme", options => { });
}); Now, you can control the authentication with the client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(scheme: "TestScheme"); Tested in net6.0. |
@wtgodbe think something is broken with the both, it readds this label to this issue (which is not a PR..) |
Sorry about that, please see #53859 |
Is there an existing issue for this?
Describe the bug
Override authentication as described in https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-7.0#mock-authentication using Microsoft.AspNetCore.Mvc.Testing does not work.
The issue appears to be similar to #37680 where configuration cannot be overridden via the new webapi templates (without startup.cs).
It appears that
will go off after a ConfigureTestServices method in WebApplicationFactory and overriding it.
Omitting the above add authentication does trigger the the fake principal and authentication.
I created a repo case over here
https://github.com/kaylumah/WebApiOverrideConfigIssue
Expected Behavior
No response
Steps To Reproduce
No response
Exceptions (if any)
No response
.NET Version
net7
Anything else?
No response
The text was updated successfully, but these errors were encountered: