ASP.NET Core 3.1 Cookie 身份验证 - 滑动过期不起作用

问题描述 投票:0回答:1

我正在尝试在 ASP.NET Core 3.1 cookie 身份验证中实现滑动过期,无论我尝试什么,cookie 似乎都不会刷新。

我的配置服务如下所示:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
    options.SlidingExpiration = true;
    options.Cookie.MaxAge = new TimeSpan(0, 1, 0);
});

我的登录过程如下所示:

var claims = new List<Claim>
{
    new Claim(ClaimTypes.Name, "the user"),
    new Claim(ClaimTypes.Role, "Administrator"),
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
    AllowRefresh = true,
    IsPersistent = true
};
await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    new ClaimsPrincipal(claimsIdentity),
    authProperties);

cookie 正确地显示有 1 分钟的过期时间,但无论我登录后多久刷新一次页面,cookie 都不会刷新以延长过期时间。我尝试过使用和不使用 HTTPS。我还尝试摆弄各种其他参数,这些参数似乎不相关,而且果然它们没有任何区别。

我找不到任何在不使用 Identity 的情况下在 Core 3.1 上设置滑动过期的代码示例,但这里有 Identity 的文档 https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity -configuration?view=aspnetcore-3.1 确实包含使用滑动过期的代码示例。无奈之下我用 Identity 创建了一个新的测试项目并复制到代码示例中:

services.ConfigureApplicationCookie(options =>
{
    options.AccessDeniedPath = "/Identity/Account/AccessDenied";
    options.Cookie.Name = "YourAppCookieName";
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
    options.LoginPath = "/Identity/Account/Login";
    options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
    options.SlidingExpiration = true;
});

这也不起作用。所以目前在我看来,滑动过期在 3.1 中已经完全被打破了。有谁有滑动到期按预期工作的示例吗?

asp.net-core asp.net-authentication
1个回答
0
投票

我在 dotnet 8 上也遇到了同样的问题。似乎 cookie 只在经过授权检查的控制器上重新发布,例如与

[Authorize]
或类似的东西:

app.MapGet("/hello", () => "Hello world!").RequireAuthorization();

在未经授权的普通控制器上检查它不会更新cookie。

© www.soinside.com 2019 - 2024. All rights reserved.