ASP.NET Core持久化身份验证 - 自定义Cookie身份验证

6

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

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

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

2个回答

6
根据文档,IsPersistent授予的持久性仅意味着身份验证将在浏览会话中持续存在(即,即使关闭浏览器也会保留)。您需要结合使用Persistence 才能为cookie设置过期时间。可以使用CookieAuthenticationOptions (MSDN)来设置cookie的过期时间,使用ExpireTimeSpan选项。如果没有持久性,则可以使用AuthenticationOptions中的ExpiresUtc选项来设置身份验证的过期时间。

好的,我会尝试一下。只有一个问题,文档上说:ExpiresUtc和IsPersistent属性是互斥的。这不意味着我不能同时使用它们吗? - Wakam Fx
@GlobalFx,因此绝对到期时间(通过ExpiresUtc)将拒绝设置的Cookie,即使用户没有关闭浏览器。_IsPersistent_表示用户的身份验证生命周期由CookieAuthenticationOptions决定。 将isPersistent设置为false意味着用户仅在当前浏览会话中进行身份验证,该会话将在关闭浏览器时清除。 - Stephen Vernyi
好的,解决方案是在“ConfigureServices”中将“_IsPersistent_”设置为true,并将“_ExpireTimeSpan_”设置为一年,而不设置“_ExpiresUtc_”。用户每年只需要登录一次,对吧? - Wakam Fx
1
我相信是这样的!无论你的应用程序使用什么样的cookies,如果你没有设置持久性,那么在关闭浏览器时cookies会被清除。如果你设置了持久性,那么cookies需要一个由你的TimeSpan设置的过期日期。 - Stephen Vernyi
太好了!你想更新你的答案,这样我就可以接受它了吗? - Wakam Fx

3

在实现持久化 cookie 认证时,有几个需要注意的事项。

在 Startup.cs 中配置滑动过期时间。如果您明确设置所需的值并不使用默认设置,则会更清晰。

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");
}

来自文档:


这应该标记为已接受答案。 - dellos
调用.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie之间有关联吗? - Omu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接