Tab*_*Tab 5 c# asp.net-mvc asp.net-core-2.0
在我的 ASP.NET MVC Core 2.0 应用程序中,我已设置为使用 cookie 身份验证方案而不使用 Identity,因为我们有自己的后端身份验证存储和 api。
身份验证和授权每次都能完美运行。
但是,无论登录/会话在大约 30 分钟后过期。您可以看到我们将身份验证 cookie 和会话 cookie 的超时设置为 120 分钟。
应用信息:
更新:替换services.AddMemoryCache()为services.AddDistributedRedisCache(..)- 测试以查看其工作原理
启动文件
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();
}
Run Code Online (Sandbox Code Playgroud)
账户控制器.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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2058 次 |
| 最近记录: |