Vio*_*tPL 6 c# authentication cookies asp.net-core asp.net-core-2.1
我正在构建 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));
}
Run Code Online (Sandbox Code Playgroud)
现在,我如何调用 AuthenticationProperties 来从 ExpiresUtc 获取/设置我所有页面上的数据?假设设置有效,因为我定义了参数 AllowRefresh = true。但是得到是我不知道该怎么做的事情。
在理想情况下,我想在部分页面上获取它,就像我获取身份验证数据一样:
@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor;
@if (HttpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
(...)
Run Code Online (Sandbox Code Playgroud)
简短回答
HttpContext.Request.Cookies。解释
服务器在创建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 将作为cookies标头中 HTTP 请求的一部分发送到服务器。
请求标头示例:cookies: my-token: FOO; my-other-token: BAR
在这种情况下,仅将 cookie 名称和 cookie 值发送到服务器。这意味着服务器不会收到 cookie 何时过期的信息。
| 归档时间: |
|
| 查看次数: |
1039 次 |
| 最近记录: |