在ASP.net核心身份(UserManager和SignInManager)是否可以立即禁止用户?

JRe*_*eam 10 c# asp.net asp.net-identity

我正在尝试找到一种方法来为我正在开发的应用程序的管理员提供一种有效的方法来快速锁定已经离开公司或被确定为行为的用户,该用户可以立即锁定或使用该应用程序.

到目前为止看起来我可以;

//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");
Run Code Online (Sandbox Code Playgroud)

但如果用户的cookie过期时间为30分钟,则上述情况无法解决.这意味着,如果用户已经过身份验证,并且在我用于使Cookie保持有效的默认时间内,则用户可以继续使用该应用.

是否有用户管理器方法更改cookie被反弹的"检查"?我假设[Authorize]属性标签正在检查cookie,而不是在表中未公开的Identity内.想知道我如何更改"检查"值以使它们与cookie会话不匹配?

Dav*_*idG 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

以及一个易于配置的扩展:

public static class UserDestroyerMiddlewareExtensions
{
    public static IApplicationBuilder UseUserDestroyer(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<UserDestroyerMiddleware>();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在在你的Configure方法中Startup.cs,Identity在设置之后添加这一行:

app.UseUserDestroyer();
Run Code Online (Sandbox Code Playgroud)

现在,这个中间件应该在每个请求上运行,检查用户是否应该注销.您可能希望简化此过程,方法是不在每个请求中访问数据库,而是使用某种最近删除的用户的缓存列表.