在Blazor Server中使用SignInAsync方法登录时,会自动创建名为“.AspNetCore.Cookies”的身份验证Cookie,它的过期时间默认为会话结束。但有时我们希望让Cookie的过期时间更长,例如一个月或更长的时间。
为了控制Cookie的过期时间,我们需要传递一个AuthenticationProperties对象给SignInAsync方法,并在该对象中设置ExpiresUtc属性。
例如,以下代码将创建一个过期时间为30天的Cookie:
var claims = new List
{
new Claim(ClaimTypes.Name, "john"),
new Claim(ClaimTypes.Role, "admin")
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authenticationProperties = new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTimeOffset.UtcNow.AddDays(30)
};
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authenticationProperties);
在上面的代码中,我们创建了一个ClaimsIdentity对象和一个AuthenticationProperties对象。然后我们调用HttpContext.SignInAsync方法,并将这两个对象作为参数传递给它。这将创建包含我们的身份验证信息和过期时间的Cookie。
注意,我们在AuthenticationProperties对象中设置IsPersistent属性为true,以便Cookie在浏览器关闭后仍然存在。
通过这种方式,我们就可以在Blazor Server中控制身份验证Cookie的行为,包括过期时间等。