c# - 如果帐户过期,则强制用户注销
问题描述
如果他的帐户过期,我正试图强制用户注销。我正在使用 Asp.Net MVC core 3,这是我得到的解决方案之一。
我在服务“ValidateAsync”下添加了新类。
public class ValidateAsync
{
public static async Task ValidatingAsync(CookieValidatePrincipalContext context)
{
context = context ?? throw new ArgumentNullException(nameof(context));
var claimsIdentity = context.Principal.Identity as ClaimsIdentity;
if (claimsIdentity?.Claims == null || !claimsIdentity.Claims.Any())
{
await RejectPrincipal();
return;
}
UserManager<IdentityUser> userManager = context.HttpContext.RequestServices.GetRequiredService<UserManager<IdentityUser>>();
var user = await userManager.FindByNameAsync(context.Principal.FindFirstValue(ClaimTypes.NameIdentifier));
if (user == null || user.SecurityStamp != context.Principal.FindFirst(new ClaimsIdentityOptions().SecurityStampClaimType)?.Value)
{
await RejectPrincipal();
return;
}
async Task RejectPrincipal()
{
context.RejectPrincipal();
await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
}
}
}
在 Startup 类中,我在“ConfigureServices”方法中添加:
services.ConfigureApplicationCookie(options =>
{
options.Events = new CookieAuthenticationEvents
{
OnValidatePrincipal = ValidateAsync
};
}).Configure<SecurityStampValidatorOptions>(options =>
{
options.ValidationInterval = TimeSpan.Zero;
});
在这里,我有一个后台进程,它将用户设置为过期,同时如果他在过期后登录,我想强制他注销。
public async Task SetExpired()
{
foreach(var item in _db.Institution)
{
if (item.SubscriptionEndDate != null)
{
if (item.SubscriptionEndDate == DateTime.Today)
{
item.Status = SD.StatusExpired;
//Here I want to check if the user is logged in, then force logout should be done.
Guid securityStamp = Guid.NewGuid();
item.SecurityStamp = securityStamp;
}
}
}
await _db.SaveChangesAsync();
}
我不知道我的方法是否应该按预期工作。但是启动类中的 ValidateAsync 显示以下错误:
CS0119:“ValidateAsync”是一种类型,在给定上下文中无效。
非常感谢任何帮助。
解决方案
一个小小的误用。改变
options.Events = new CookieAuthenticationEvents
{
OnValidatePrincipal = ValidateAsync
};
至
options.Events = new CookieAuthenticationEvents
{
OnValidatePrincipal = ValidateAsync.ValidatingAsync
};
推荐阅读
- sql - 更改外键约束主键错误
- javascript - 单击时将特定项目添加到购物车
- airflow - 气流任务卡在“已计划”状态,并且在回填期间永远不会运行
- django - 在生产环境中运行迁移出现问题(即 Heroku 平台)
- linux - 获取正在运行的进程的环境变量
- javascript - 打字稿map.get返回未定义
- excel - Excel公式获取前三个非零值并获取它们的相应标题
- php - 管理员:服务器是否在本地运行并接受 Unix 域套接字“/var/pgsql_socket/.s.PGSQL.5432”上的连接?
- php - 我该如何解决加载此静态页面的减速问题?
- google-bigquery - BigQuery 可以使用通配符表名和 table_suffix,但我正在寻找类似的解决方案,如通配符数据集和 dataset_suffix