如何从HttpContext中获取基于cookie的身份验证的过期时间?

7
我正在构建一个C# (.net core 2.1) Razor Page网站。登录机制将基于此处的文档进行操作——因此在cookie中使用令牌(如果我理解正确):https://learn.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-2.1 假设我设置了3分钟的会话,并且如果用户正在积极使用网站,我将重置此值。如果他没有这样做,在令牌过期前30秒,我想向他显示消息,例如“要么做点事情,要么您将被登出”。
我的问题是,我找不到获取此“过期”时间的方法。以下是我验证和存储数据的方式:
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
    ReturnUrl = returnUrl;
    int iCookieLifeTime = 10;

    if (ModelState.IsValid)
    {
        var user = await AuthenticateUser(Input.UserName, Input.License, Input.Password, Input.KeepLogged);

        if (user == null)
        {
            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
            return Page();
        }

        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, user.UserName),
            new Claim("Password", user.Password ) )
        };

        var claimsIdentity = new ClaimsIdentity(
            claims, CookieAuthenticationDefaults.AuthenticationScheme);

        var authProperties = new AuthenticationProperties
        {
            AllowRefresh = true,
            ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(iCookieLifeTime)                    
        };

        await HttpContext.SignInAsync(
            CookieAuthenticationDefaults.AuthenticationScheme,
            new ClaimsPrincipal(claimsIdentity),
            authProperties);

        return LocalRedirect(Url.GetLocalUrl(returnUrl));
    }

现在,我该如何调用AuthenticationProperties来在所有页面上获取/设置ExpiresUtc上的数据呢?假设设置正在工作,因为我定义了参数AllowRefresh = true。但是我不知道如何获取。
在理想情况下,我希望像获取身份验证数据一样,在部分页面上获取它:
@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor;

@if (HttpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
(...)
1个回答

0

简短回答

  • 无法从HttpContext.Request.Cookies中获取cookie的过期时间。
  • 为了能够在cookie即将过期时向用户显示警告,需要在客户端实现此检查。

解释

服务器在创建cookie时设置过期时间。 在这种情况下,将set-cookie头添加到HTTP响应中并发送回客户端。

示例响应头:set-cookie: my-token: FOO; expires=Fri, 21 Apr 2023 14:11:21 GMT; domain=foobar.com; path=/; secure; samesite=strict; httponly

客户端接收响应并将cookie以及过期时间存储在浏览器中。

当客户端发出另一个请求时,cookie作为HTTP请求的一部分发送到服务器中的cookies头中。

示例请求头:cookies: my-token: FOO; my-other-token: BAR

在这种情况下,只有cookie名称和cookie值被发送到服务器。这意味着服务器不会接收到cookie何时过期的信息。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接