ASP.NET MVC 用户注销时显示消息



我正在创建一个具有Identity 2.0的应用程序,管理员可以禁止其他用户。当他们禁止他们时,他们就会退出登录(当他们提出下一个操作/请求时)。

这是我的禁令行动:

    public async Task<ActionResult> Block(ApplicationUser formuser, string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        var user = await UserManager.FindByIdAsync(id);
        user.DeleteDate = DateTime.Now;
        user.IsConfirmed = false;
        await UserManager.UpdateSecurityStampAsync(user.Id);
        return RedirectToAction("Index");
    }

UpdateSecuritStampAsync 执行注销部分。另外,我认为如果我插入Startup.Auth.cs UseCookieAuthentication会很好,因为我在那里更改了一件事,以便用户注销(如果我错过添加重要内容,请在评论中写下,我会添加它)

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account. 
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(0),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        }); 

我将默认的时间跨度从 30 分钟更改为 0(这可能是一个错误,但它有效)。这个线程的主要问题是我想创建一些东西,当用户注销时它会显示一条消息,我应该怎么做?(当管理员阻止用户时,用户在重新加载页面后会收到一条消息,指出他因使用不当或其他原因而被阻止)

最好使用锁定/解锁用户,而不是更新安全标记。请参阅如何在标识提供者中锁定和解锁帐户 Asp.Net。

public virtual async Task<IdentityResult> LockUserAccount(string userId, int? forDays)
{
    var result = await this.SetLockoutEnabledAsync(userId, true);
    if (result.Succeeded)
    {
        if (forDays.HasValue)
        {
            result = await SetLockoutEndDateAsync(userId, DateTimeOffset.UtcNow.AddDays(forDays.Value));
        }
        else
        {
            result = await SetLockoutEndDateAsync(userId, DateTimeOffset.MaxValue);
        }
    }
    return result;
}
public virtual async Task<IdentityResult> UnlockUserAccount(string userId)
{
    var result = await this.SetLockoutEnabledAsync(userId, false);
    if (result.Succeeded)
    {
        await ResetAccessFailedCountAsync(userId);
    }
    return result;
}

在您的登录操作或提供商上,您将使用

if (userManager.IsLockedOut(userId))
{
    context.SetError("invalid_grant", "The account is locked out of the system.");
    return;
}

我不确定如何在被锁定后立即通知用户而不尝试登录,因为在他/她被重定向到登录页面时您没有用户的 ID 或用户名。但是,如果您这样做,那么您可以简单地使用 IsLockedOut 方法来决定是否应该显示一个弹出窗口,说明您想对用户说什么。

最新更新