我正在尝试找到一种方法来为我正在开发的应用程序的管理员提供一种有效的方法来快速锁定已经离开公司或被认为行为方式有效的用户立即锁定或使用该应用程序。
到目前为止看起来我可以;
//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");
但如果用户的Cookie过期时间为30分钟,则上述操作无法解决。这意味着,如果用户已经过身份验证,并且在我用于使Cookie保持有效的默认时间内,则用户可以继续使用该应用。
是否有一个用户管理器方法可以更改Cookie被退回的“检查”?我假设[Authorize]属性标签正在检查cookie,而不是在表中未公开的Identity内。想知道我如何更改“检查”值以使它们与cookie会话不匹配?
答案 0 :(得分:7)
您可以使用针对每个请求运行的某些中间件来执行此操作。首先创建你的中间件类,如下所示:
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>();
}
}
现在在Configure
的{{1}}方法中,在设置Startup.cs
后添加此行:
Identity
现在,这个中间件应该在每个请求上运行,检查用户是否应该注销。您可能希望简化此过程,方法是不在每个请求中访问数据库,而是使用某种最近删除的用户的缓存列表。