Last active
October 22, 2019 19:27
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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