首页 > 解决方案 > 如何在基于 cookie 的身份验证中从 HttpContext 获取过期时间?

问题描述

我正在构建 C# (.net core 2.1) Razor Page 站点。登录机制将根据此处的文档工作 - 所以 cookie 中的令牌(如果我理解正确的话):https ://docs.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)
(...)

标签: c#authenticationasp.net-corecookiesasp.net-core-2.1

解决方案


推荐阅读