c# - 每次更改和重新编译 blazor 代码后,如何停止 cookie 失效?
问题描述
我正在使用托管的 Blazor WebAssembly 项目模板,并且在将 cookie 设置为主要身份验证方法(也适用于 API)之后,一切都很好,直到我更改了一行代码(前端或后端),自动编译开始并重新加载网页(感谢“Start without Debugging”),但这次 auth cookie 似乎无效,我似乎不再登录。
有没有办法阻止这种行为?或者一种阻止cookie auth在不同编译之间变化的方法?
以下是我的 CookieAuthenticationEvents 实现/覆盖:
public class CookieAuth : CookieAuthenticationEvents
{
readonly IUserService UserRepository;
public CookieAuth(IUserService userRepository)
{
UserRepository = userRepository;
}
public override Task RedirectToLogin(RedirectContext<CookieAuthenticationOptions> context)
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return Task.CompletedTask;
}
public override Task RedirectToAccessDenied(RedirectContext<CookieAuthenticationOptions> context)
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return Task.CompletedTask;
}
public override async Task ValidatePrincipal(CookieValidatePrincipalContext context)
{
var userPrincipal = context.Principal;
var userId = (from c in userPrincipal.Claims
where c.Type == ClaimTypes.NameIdentifier
select c.Value).FirstOrDefault();
var isTeacherAndBlocked = await UserRepository.IsTeacherAndIsBlocked(userId);
if (isTeacherAndBlocked)
{
context.RejectPrincipal();
await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return;
}
var lastChanged = (from c in userPrincipal.Claims
where c.Type == "LastChanged"
select c.Value).FirstOrDefault();
if (!DateTime.TryParse(lastChanged, out DateTime lastChangedDate))
{
context.RejectPrincipal();
await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return;
}
if (!await UserRepository.ValidateLastChanged(lastChanged, userId))
{
context.RejectPrincipal();
await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
}
}
}
同时UserRepository.ValidateLastChanged(...)
检查获取的日期字符串是否与数据库中的日期字符串匹配(这是一种判断用户是否更改密码然后从另一台设备转到旧会话的方法,在这种情况下,我希望那种会话无效)
然后是通常的Startup.cs
cookie 配置:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromHours(1);
options.Cookie.SameSite = SameSiteMode.Lax;
options.Cookie.Name = "wtf";
options.EventsType = typeof(CookieAuth);
options.SlidingExpiration = true;
});
解决方案
没关系,发现这是字符串日期之间的比较问题,只是不要这样做,用刻度线。:D
推荐阅读
- javascript - 如何获取 recaptcha 值以便可以在条件检查中使用
- python - 函数内的“for”循环
- reactjs - 提交的数据在没有刷新的情况下不呈现 - 反应
- jquery - 如何在工具提示中使用 HTML?
- git - ubuntu 服务器上的图形 Gitolite
- c# - 如何通过 Forge 存储桶下载 *around* Web 应用程序,而不是 *通过* Web 应用程序?
- ios - 如何解决此错误“尝试在 Xcode 中将 'com.example' 替换为您的签名 ID:打开 ios/Runner.xcworkspace”
- visual-studio-code - 在哪里可以找到 vscode 撤消堆栈文档
- c# - 我真的需要在这里创建一个新的交易吗?
- php - 从 JSON 数组 PHP 嵌套数组中获取价值