c# - 如何在基于 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)
(...)
解决方案
推荐阅读
- javascript - Visual Studio 2019 Javascript XML 注释未显示
- vhdl - 我可以使用嵌入式实体端口的长度吗?
- excel - 如何在excel中动态计算所选学生和科目的分数?
- php - 我不明白我们收到的电子邮件中插入的一些 php 代码
- rust - 生命周期参数的语义
- ruby-on-rails - 通过 webpacker 实现一个无依赖库
- amazon-web-services - 为什么我需要在 API 网关中创建自定义域?
- authentication - 如何将基本身份验证添加到 Mapbox 中 WMS 源的标头
- wiremock - Wiremock 没有模板化请求路径段
- macos - OSX:Chrome 无法连接到 .localhost-domains。拒绝连接