ASP.NET核心持续身份验证 - 自定义Cookie身份验证



我正在尝试获得持久连接,因此用户只需使用一次密码即可。我已经使用了此文档:https://learn.microsoft.com/en-us/aspnet/core/security/authentication/cookie?tabs=aspnetcore2x,但一段时间后用户仍然断开连接。

>
await HttpContext.SignInAsync(
                    CookieAuthenticationDefaults.AuthenticationScheme,
                    principal,
                    new AuthenticationProperties
                    {
                        IsPersistent = true
                    });

我该怎么做才能获得真正持久的连接?

根据文档,

iSpypysterent授予的持久性仅是为了暗示身份验证将通过浏览会话持续存在(也就是说,即使在浏览器关闭时也保留了身份验证)。您需要持久性的组合来为cookie设置到期时间。可以使用 expiretimespan 选项。

不持久,可以使用AuthenticationOptions中的 expiresutc 选项设置身份验证,

当实现持久cookie身份验证时,您应该注意到的事情。

在startup.cs中为cookie配置滑动到期。如果您明确设置所需的值并且不使用默认设置。

将更清楚。
private void ConfigureAuthentication(IServiceCollection services)
{
    services
        .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {                 
            // true by default   
            options.SlidingExpiration = true;
            // 14 days by default
            options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
        });
}

当用户检查标志"记住我"时配置cookie以在浏览器会话中持续存在并设置绝对到期(只要您需要)。这种设置将覆盖SlidingExpiration和ExpireTimesPAN。在登录操作中:

List<Claim> claims = new List<Claim>();
// Prepare user claims...
                
var userIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
AuthenticationProperties authenticationProperties = new AuthenticationProperties() { IsPersistent = model.RememberMe };
if (model.RememberMe)
{
    // One month for example
    authenticationProperties.ExpiresUtc = DateTimeOffset.UtcNow.AddMonths(1);
}
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, authenticationProperties);

令人讨厌的数据保护。在旧的经典ASP.NET WebForms中记住MachineKey。否则,每个IIS应用程序池重新启动后,Cookie将被重置。在startup.cs认证之前,您应该配置数据保护。将密钥存储在应用程序的根文件夹中:

private void ConfigureDataProtection(IServiceCollection services, IWebHostEnvironment environment)
{
    var keysDirectoryName = "Keys";
    var keysDirectoryPath = Path.Combine(environment.ContentRootPath, keysDirectoryName);
    if (!Directory.Exists(keysDirectoryPath))
    {
        Directory.CreateDirectory(keysDirectoryPath);
    }
    services.AddDataProtection()
          .PersistKeysToFileSystem(new DirectoryInfo(keysDirectoryPath))
          .SetApplicationName("YourApplicationName");
}

来自文档:

  • https://lealen.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=ply=plnetcore-5.0
  • https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/configuration/overview?view= suppnetcore-5.0

最新更新