我开始使用ASP.Net Core 2.2开发网站。我正在通过自定义 cookie 身份验证(不是身份)来实现登录/注销。
请查看或克隆repo:
git clone https://github.com/mrmowji/aspcore-custom-cookie-authentication.git .
...或阅读以下代码片段。
这是中的代码Startup.cs
:
public void ConfigureServices(IServiceCollection services) {
...
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options => {
options.LoginPath = new PathString("/login");
options.ExpireTimeSpan = TimeSpan.FromDays(30);
options.Cookie.Expiration = TimeSpan.FromDays(30);
options.SlidingExpiration = true;
});
...
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
...
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
...
这是Login
操作代码:
public async Task<IActionResult> Login(LoginViewModel userToLogin) {
var username = "username"; // just to test
var password = "password"; // just to test
if (userToLogin.UserName == username && userToLogin.Password == password) {
var claims = new List<Claim> {
new Claim(ClaimTypes.Name, "admin"),
new Claim(ClaimTypes.Role, "Administrator"),
};
var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties {
AllowRefresh = true,
ExpiresUtc = DateTimeOffset.UtcNow.AddDays(10),
IsPersistent = true,
};
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
...
Cookie 已按预期设置。我有一个.AspNetCore.Cookies
有效期为 10 天后的 cookie。但大约 30 分钟后,用户退出。即使在浏览器关闭后,如何强制经过身份验证的用户保持登录状态?