Question
How to Require Authentication for Each Browser Instance with ASP.NET Core?
Our application is in ASP.NET Core (.NET 6) using a MVC architecture with an authentication model that creates an "auth" cookie. After a user logs into the application with a Browser (Chrome), opening a new instance of the browser and navigating to the application allows them access without the logon page. We would like the application to require authentication for any browser instance. The following code is from a test application that I wrote to see if the issue was our application or not (test application has same behavior):
public const string APP_AUTH_SCHEME = "MyAuthScheme";
Program.cs:
// Services:
builder.Services.AddAuthentication(AuthModel.APP_AUTH_SCHEME)
.AddCookie(AuthModel.APP_AUTH_SCHEME, options =>
{
options.LoginPath = new PathString("/account/logon");
options.LogoutPath = new PathString("");
options.Cookie.Name = AuthModel.APP_AUTH_SCHEME;
options.Cookie.SameSite = SameSiteMode.Strict;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});
builder.Services.AddHttpContextAccessor();
// Middleware Pipeline:
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Note: I added the Cookie.SameSite and SecurePolicy, but they did not change the behavior.
Account Controller:
// async Logon Action:
var claims = new[] {
new Claim(ClaimTypes.Name, model.UserName),
new Claim(ClaimTypes.Role, "User")
};
var claimsIdentity = new ClaimsIdentity(claims, AuthModel.APP_AUTH_SCHEME);
await _httpContextAccessor.HttpContext.SignInAsync(AuthModel.APP_AUTH_SCHEME,
new ClaimsPrincipal(claimsIdentity),
new AuthenticationProperties() { IsPersistent = false });
The Action of a Controller that requires authorization is marked with the [Authorize] tag. The above code works great when the user first accesses the application, but we need each browser instance to require authentication.
In advance, Thank you for your help!