【发布时间】:2018-09-29 05:18:39
【问题描述】:
问题
在我的 ASP.NET MVC Core 2.0 应用程序中,我已设置为使用 cookie 身份验证方案而不使用 Identity,因为我们有自己的后端身份验证存储和 api。
身份验证和授权每次都能完美运行。
但是,无论登录/会话如何在大约 30 分钟后过期。您可以看到我们将身份验证 cookie 和会话 cookie 的超时时间都设置为 120 分钟。
申请信息:
- 平台:.Net 4.7.x (Windows)
- 框架:Asp.Net Core 2.x
- IIS 用作代理服务器
欢迎任何有关如何解决此问题的帮助或意见
代码
更新:将 services.AddMemoryCache() 替换为 services.AddDistributedRedisCache(..) - 测试以了解其工作原理
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedRedisCache(options =>
{
options.Configuration = "localhost";
options.InstanceName = "CoreTestInstance";
});
services.AddAuthentication("CookieAuthenticationScheme")
.AddCookie("CookieAuthenticationScheme", options =>
{
options.Cookie.Name = authSettings.Name;
options.Cookie.HttpOnly = false;
options.Cookie.Expiration = TimeSpan.FromMinutes(120);
options.ExpireTimeSpan = TimeSpan.FromMinutes(120);
options.AccessDeniedPath = new PathString("/Errors/StatusCodeErrors/401");
options.LoginPath = "/Account/Login";
});
// services.AddMemoryCache();
services.AddSession(options =>
{
options.Cookie.Name = sessSettings.Name;
options.Cookie.HttpOnly = false;
options.IdleTimeout = TimeSpan.FromMinutes(120);
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Errors/Default");
}
app.UseStatusCodePagesWithRedirects("/Errors/StatusCodeErrors/{0}");
app.UseStaticFiles();
app.UseAuthentication();
app.UseSession();
app.UseMvc();
}
AccountController.cs
[HttpPost("Login")]
public async Task<IActionResult> Login(AccountModel model)
{
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, model.UserName));
claims.Add(new Claim(ClaimTypes.Role, "Administrator", ClaimValueTypes.String, model.UserName));
var identity = new ClaimsIdentity(claims, "login");
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync("CookieAuthenticationScheme", principal);
}
【问题讨论】:
标签: c# asp.net-mvc asp.net-core-2.0