Skip to content

Instantly share code, notes, and snippets.

@GeorgDangl
Last active October 22, 2019 19:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GeorgDangl/f8cedc417dc1e4cacbcff8eedf9e26a0 to your computer and use it in GitHub Desktop.
Save GeorgDangl/f8cedc417dc1e4cacbcff8eedf9e26a0 to your computer and use it in GitHub Desktop.
Perform user sign in via request headers for integration testing with Asp.Net Core TestHost & the Asp.Net Core Identity framework
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
// Seed with integration tests specific data
ServerInitialization.InitializeIntegrationTestsDatabase(app.ApplicationServices).Wait();
}
app.UseStaticFiles();
app.UseIdentity();
// To log in a user for integration tests
// DO NOT USE IN PRODUCTION
app.Use(next => async context =>
{
await SignInIntegrationTestUser(context);
await next.Invoke(context);
});
app.UseMvc();
}
public async Task SignInIntegrationTestUser(HttpContext context)
{
var integrationTestsUserHeader = context.Request.Headers["IntegrationTestLogin"];
if (integrationTestsUserHeader.Count > 0)
{
var userName = integrationTestsUserHeader[0];
var userManager = context.RequestServices.GetRequiredService<UserManager<ApplicationUser>>();
var user = await userManager.FindByEmailAsync(userName);
if (user == null)
{
return;
}
var signInManager = context.RequestServices.GetRequiredService<SignInManager<ApplicationUser>>();
var userIdentity = await signInManager.CreateUserPrincipalAsync(user);
context.User = userIdentity;
}
}
public static HttpClient AdminClient
{
get
{
var client = _testServer.CreateClient();
client.DefaultRequestHeaders.Add("IntegrationTestLogin", "admin@example.com");
return client;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment