首页 > 解决方案 > 传递给 HttpContext.SignInAsync 和 CookieAuthenticationOptions.ExpireTimeSpan 的时间之间的差异

问题描述

传递给Microsoft.AspNetCore.Authentication.AuthenticationProperties.ExpiresUtcinHttpContext.SignInAsync和的日期 和有什么不一样Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationOptions.ExpireTimeSpan

两者的文档都说它控制time at which the authentication ticket expires. 那么一段时间后我应该使用哪个来放弃登录?

标签: c#asp.net-core

解决方案


基本上,是未设置时使用CookieAuthenticationOptions.ExpireTimeSpan默认AuthenticationProperties.ExpiresUtc

登录时CookieAuthenticationHandler中的逻辑是这样的:

if (!signInContext.Properties.ExpiresUtc.HasValue)
{
    signInContext.Properties.ExpiresUtc = issuedUtc.Add(Options.ExpireTimeSpan);
}

ExpiresUtc当身份验证属性中有明确的设置时,就会使用它。否则,到期日期计算为发布时间加上ExpireTimeSpan已配置的时间。

因此,您应该将 配置CookieAuthenticationOptions为具有默认值,然后AuthenticationProperties在您想要覆盖它时通过显式传递。例如,您需要通过AuthenticationProperties设置持久性 cookie,但除非您有一些其他逻辑来计算到期日期,否则仅保留选项中的默认持续时间可能更容易。


推荐阅读