I'm attempting to write integration tests for an ASP.Net Core 3.1 API that I'm writing. I'm using the WebApplicationFactory<> class in order to create an HttpClient for calling into the API.
_Factory = new WebApplicationFactory<Startup>()
.WithWebHostBuilder(b =>
{
b.ConfigureTestServices(services =>
{
services.AddAuthentication("Test")
.AddScheme<AuthenticationSchemeOptions, MyAuthHandler>("Test", options => { });
RegisterTestServices(services);
});
});
With:
public class MyAuthHandler: AuthenticationHandler<AuthenticationSchemeOptions>
{
public MyAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) { }
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var claims = new[] {new Claim("preferred_username", "mchu")};
var identity = new ClaimsIdentity(claims, "Test");
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, "Test");
var result = AuthenticateResult.Success(ticket);
return Task.FromResult(result);
}
}
This successfully allows me to retrieve an HttpClient that can call out to my endpoints (decorated with [Authorize]) so I don't get 401 errors. However, some of my tests are failing due to permissions problems upon attempting to access network shares.
In an actual IIS deployment, our application pool would be using an identity that has read/write access to those shares.
Is there anything I can do to ensure that my API code runs with permissions that can access those protected resources? Our existing integration test code (for non-ASP.Net Core code--this is a conversion) gets around this problem by simply performing the particular operations in an administrator impersonation context. I'm fine with doing that for these new tests, as well.
However, without yet understanding a whole lot about WebApplicationFactory<> (or any bit of the ASP.Net Core middleware pipeline, really), I'm not sure how I would go about doing this.
ASP.NET Core doesn't implement impersonation. Apps run with the app's identity for all requests, using app pool or process identity. If the app should perform an action on behalf of a user, use WindowsIdentity.RunImpersonated in a terminal inline middleware in Startup.Configure. Run a single action in this context and then close the context.
More details you can refer to this document
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments