Asp.net identity 如何使用.netcore 2.0标识和cookie身份验证正确设置会话超时
我正在尝试在asp.netcore 2.0 MVC应用程序中使用身份验证和cookie身份验证。我想将会话超时设置为150天左右,这样登录的用户就不需要在很长时间内再次登录。我设置Asp.net identity 如何使用.netcore 2.0标识和cookie身份验证正确设置会话超时,asp.net-identity,asp.net-core-2.0,session-timeout,cookie-authentication,Asp.net Identity,Asp.net Core 2.0,Session Timeout,Cookie Authentication,我正在尝试在asp.netcore 2.0 MVC应用程序中使用身份验证和cookie身份验证。我想将会话超时设置为150天左右,这样登录的用户就不需要在很长时间内再次登录。我设置options.ExpireTimeSpan=TimeSpan.FromDays(150)但会话在几分钟后关闭,即使用户正在积极使用应用程序 我正在遵循官方文件,我的Startup.cs上有以下内容: 在ConfigureServices方法中: services.AddIdentity<User, Ro
options.ExpireTimeSpan=TimeSpan.FromDays(150)代码>但会话在几分钟后关闭,即使用户正在积极使用应用程序
我正在遵循官方文件,我的Startup.cs上有以下内容:
在ConfigureServices
方法中:
services.AddIdentity<User, Role>()
.AddDefaultTokenProviders();
// Identity Services
services.AddTransient<IUserStore<User>, UserService>();
services.AddTransient<IRoleStore<Role>, RoleService>();
services.Configure<IdentityOptions>(options =>
{
// Password settings
options.Password.RequireDigit = false;
options.Password.RequiredLength = 8;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequireLowercase = false;
options.Password.RequiredUniqueChars = 3;
// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 10;
options.Lockout.AllowedForNewUsers = true;
// User settings
options.User.RequireUniqueEmail = true;
});
services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromDays(150);
options.LoginPath = "/User/Login";
options.LogoutPath = "/User/Logout";
options.AccessDeniedPath = "/User/AccessDenied";
options.SlidingExpiration = true;
});
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
我是否缺少任何配置?我想我会把有效期设为150天
提前谢谢
编辑:问题似乎出在ValidationInterval上。我发现这个问题:
我尝试将ValidationInterval设置为一个较大的值,现在会话没有关闭,用户也没有意外注销。这是设置间隔的代码:
services.Configure<SecurityStampValidatorOptions>(options =>
options.ValidationInterval = TimeSpan.FromDays(150));
services.Configure(选项=>
options.ValidationInterval=TimeSpan.FromDays(150));
我想我必须看看安全戳验证器是如何工作的,并正确定义验证间隔,这样会话不会意外关闭,而且不会因为陈旧的cookie而忽略对用户权限的修改。您设置的过期时间仅适用于cookie(客户端),还有一个必须持久化的服务器端组件。这是通过IDistributedCache
实现的,IDistributedCache默认为MemoryDistributedCache
实现。换句话说,内存持久性。内存中是进程绑定的,因此如果停止并重新启动应用程序,应用程序池将在IIS中回收,服务器将重新启动,等等。所有这些都会消失。此外,如果您有多个worker,那么每个worker都有自己独立的内存。将分布式缓存配置为使用SQL Server或Redis.Ok。谢谢你的回答!我将检查服务器端部分。再次感谢。为了澄清@ChrisPratt,我不会在会话中保留任何数据。我只使用标识来管理身份验证。我认为存储在cookie中的身份验证票证足以知道票证是否过期。根据文档,ExpireTimeSpan控制存储在cookie中的身份验证票证从创建时起保持有效的时间。那么,为什么需要服务器端持久性呢?您谈论的是身份验证超时,而不是会话,这是另一回事。“会话”(您没有使用)和身份验证(您正在使用)有单独的cookie。
services.Configure<SecurityStampValidatorOptions>(options =>
options.ValidationInterval = TimeSpan.FromDays(150));