我正在尝试找到一种方法,为我正在开发的应用程序的管理员提供一种有效的方法来快速锁定已经离开公司或被确定其行为方式可能需要立即锁定或使用应用程序。
目前看来我可以;
//enable the account to be locked out
_userManager.SetLockoutEnabledAsync(ApplicationUser user, true);
//Set an arbitrary date way into the future to lock them out until I want to unlock them
_userManager.SetLockoutEndDateAsync(ApplicationUser user, "01/01/2060");
但是如果用户有一个过期时间为 30 分钟的 cookie,则上述问题不会解决。意思是,如果用户已经通过身份验证并且在我用于 cookie 保持有效的默认时间内,他们可以继续使用该应用程序。
是否有用户管理器方法可以更改 cookie 被退回的“检查”?我假设 [Authorize] 属性标签正在根据 Identity 中未在表中公开的内容检查 cookie。想知道如何更改“检查”值以使它们不匹配 cookie session ?
最佳答案
您可以使用针对每个请求运行的一些中间件来执行此操作。首先创建您的中间件类,如下所示:
public class UserDestroyerMiddleware
{
private readonly RequestDelegate _next;
public UserDestroyerMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext,
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager)
{
if (!string.IsNullOrEmpty(httpContext.User.Identity.Name))
{
var user = await userManager.FindByNameAsync(httpContext.User.Identity.Name);
if (user.LockoutEnd > DateTimeOffset.Now)
{
//Log the user out and redirect back to homepage
await signInManager.SignOutAsync();
httpContext.Response.Redirect("/");
}
}
await _next(httpContext);
}
}
还有一个扩展使其易于配置:
public static class UserDestroyerMiddlewareExtensions
{
public static IApplicationBuilder UseUserDestroyer(this IApplicationBuilder builder)
{
return builder.UseMiddleware<UserDestroyerMiddleware>();
}
}
现在,在 Startup.cs
的 Configure
方法中,在设置 Identity
之后添加此行:
app.UseUserDestroyer();
现在这个中间件应该在每个请求上运行,检查用户是否应该注销。您可能希望简化此过程,使其不会在每次请求时都访问数据库,而是使用某种缓存的最近删除的用户列表。
关于c# - 在 ASP.net 核心身份(UserManager 和 SignInManager)中,是否可以立即禁止用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42357026/