2017-10-19 172 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