首页 > 解决方案 > Cookie 过期值在 CookieAutenticationHandler 中被忽略

问题描述

我一直在尝试为我的会话 cookie 设置过期时间。所以起初,我以这种方式配置了我的 Cookie 处理程序:

services.AddAuthentication(options =>
{
    options.DefaultScheme = "Cookies";
    options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies", options => 
{
    options.Cookie.Expiration = TimeSpan.FromSeconds(3600);
})
.AddOpenIdConnect(...

虽然看起来很简单,但事实并非如此。cookie 始终作为会话创建(不持久)。

我一直在探索CookieAuthenticationHandler,我发现了这个:

protected async override Task HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
{
    if (user == null)
    {
        throw new ArgumentNullException(nameof(user));
    }

    properties = properties ?? new AuthenticationProperties();

    _signInCalled = true;

    // Process the request cookie to initialize members like _sessionKey.
    await EnsureCookieTicket();
    var cookieOptions = BuildCookieOptions();
    ...
}

令人惊讶的是,在方法中BuildCookieOptions设置为 null 我在启动时配置的过期时间:

private CookieOptions BuildCookieOptions()
{
    var cookieOptions = Options.Cookie.Build(Context);
    // ignore the 'Expires' value as this will be computed elsewhere
    cookieOptions.Expires = null;

    return cookieOptions;
}

它说“过期”值将在其他地方计算。

最后,我在另一篇文章中看到,当使用 OpenId 使用的 RemoteAuthenticationHandler 时,处理程序会触发一个 OnTicketRecived 事件,可以通过在 OpenId 处理程序的配置中实现此事件来设置过期:

.AddOpenIdConnect("oidc", options =>
{
    options.SignInScheme = "Cookies";
    options.ClientId = "client";

    options.Events.OnTicketReceived = async (context) => 
    {
        context.Properties.ExpiresUtc = DateTime.UtcNow.AddSeconds(3600);
        context.Properties.IsPersistent = true;
    };

但是,为什么这个 Expiration 值会被完全忽略呢?为什么 CookieAuthenticationOptions 让我设置此属性,但处理程序所做的第一件事是将其设置为 null?这个属性有用吗?

或者只是我错过了什么?

标签: authenticationasp.net-corecookies

解决方案


推荐阅读