2017-10-19 175 views
0

我正在使用Identity 2.0创建一个应用程序,其中管理员可以禁止其他用户。当他们禁止他们时,他们退出(当他们做出他们的下一个行动/请求时)。ASP.NET MVC在用户注销时显示消息

这里是我的禁止行为:

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)) 
      } 
     }); 

我将默认TimeSpan从30分钟更改为0(这可能是一个错误,但它的工作原理)。 这个线程的主要问题是,我想创建一些东西,当用户注销时它会显示一条消息,我应该怎么做呢? (当管理员阻止用户时,用户在他重新加载他的页面之后得到消息,表示他被阻止用于不良使用或什么)

回答

1

更好地使用锁定/解锁用户而不是更新安全印章。看看How to lock and unlock account in Asp.Net Identity provider

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; 
} 

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

+0

但是这种方法锁定了他们几天,而我的方法阻止他们,直到有人解锁他们(因为你真的不知道需要多长时间)。你这样做有问题吗? – HighSepton

+0

您可以无限期锁定某个人,然后随时解锁他们,请注意'forDays'可以为空。它已经内置,所以我宁愿你不试图重新发明轮子。 –

+0

好吧,我会尽力改变它。但是这并不能真正回答我的问题,因为我在问如何向锁定的人显示他被锁定。谢谢你的建议,尽管 – HighSepton