I have an ASP.NET Core site using AspNetCore.Identity.EntityFrameworkCore 1.1.1 and cookies to authorize/authenticate my users. No matter what I choose as my setting in the
I think the problem was that I was persisting data to a cookie with different settings.
Not sure if it's the proper way to do it, but I was able to solve the problem by using both services.AddIdentity and app.UseCookieAuthentication as below.
In ConfigureServices, set the cookie for log in:
// set the cookie for sign in
services.AddIdentity<ApplicationUser, IdentityRole>(config =>
{
// Require a confirmed email in order to log in
config.SignIn.RequireConfirmedEmail = true;
// Cookie settings
config.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromHours(10);
config.Cookies.ApplicationCookie.LoginPath = "/Account/LogIn";
config.Cookies.ApplicationCookie.LogoutPath = "/Account/LogOut";
}).AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
In Configure set the cookie scheme used to persist claims:
// Add cookie middleware to the configure an identity request and persist it to a cookie.
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookie",
LoginPath = new PathString("/Account/Login/"),
AccessDeniedPath = new PathString("/Account/Forbidden/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true,
//ExpireTimeSpan = TimeSpan.FromSeconds(10),
ExpireTimeSpan = TimeSpan.FromHours(10),
SlidingExpiration = true,
});
In the log in method, persist the claims:
await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal);
You do not need a separate CookieAuthentication middleware when you are using ASPNET identity. UseIdentity()
will do that for you and generate a cookie. You can set the "cookie options"
in the AddIdentity block of the application like so:
services.AddIdentity<ApplicationUser, IdentityRole>(config =>
{
// Require a confirmed email in order to log in
config.SignIn.RequireConfirmedEmail = true;
// Your Cookie settings
config.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays(1);
config.Cookies.ApplicationCookie.LoginPath = "/Account/LogIn";
config.Cookies.ApplicationCookie.LogoutPath = "/Account/LogOut";
}).AddEntityFrameworkStores<ApplicationDbContext().AddDefaultTokenProviders();
Also, take a look at https://stackoverflow.com/a/34981457/1137785, it gives a background of this sort of a scenario with a very good explanation.