我一直在尝试为会话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
中,将我在启动时配置的有效期设置为空:
private CookieOptions BuildCookieOptions()
{
var cookieOptions = Options.Cookie.Build(Context);
// ignore the 'Expires' value as this will be computed elsewhere
cookieOptions.Expires = null;
return cookieOptions;
}
它说“ Expires”值将在其他地方计算。
最后,我在另一篇文章中看到,当像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?此属性有用吗?
还是我错过了什么?