Disable User in ASPNET identity 2.0

后端 未结 10 1150
谎友^
谎友^ 2020-11-30 23:50

I am looking for a way to disable the user instead of deleting them from the system, this is to keep the data integrity of the related data. But seems ASPNET identity only

10条回答
  •  眼角桃花
    2020-12-01 00:20

    I upvoted Watson, as there is another public method in SignInManager that accepts TUser user instead of string userName. The accepted answer only suggests overriding the method with the username signature. Both should really be overridden, otherwise there is a means of signing in a disabled user. Here are the two methods in the base implementation:

    public virtual async Task PasswordSignInAsync(string userName, string password, bool isPersistent, bool lockoutOnFailure)
    {
      var user = await UserManager.FindByNameAsync(userName);
      if (user == null)
      {
        return SignInResult.Failed;
      }
    
      return await PasswordSignInAsync(user, password, isPersistent, lockoutOnFailure);
    }
    
    public virtual async Task PasswordSignInAsync(User user, string password, bool isPersistent, bool lockoutOnFailure)
    {
      if (user == null)
      {
        throw new ArgumentNullException(nameof(user));
      }
    
      var attempt = await CheckPasswordSignInAsync(user, password, lockoutOnFailure);
      return attempt.Succeeded
          ? await SignInOrTwoFactorAsync(user, isPersistent)
          : attempt;
    }
    

    Overriding CanSignIn seems like a better solution to me, as it gets called by PreSignInCheck, which is called in CheckPasswordSignInAsync. From what I can tell from the source, overriding CanSignIn should cover all scenarios. Here is a simple implementation that could be used:

    public override async Task CanSignInAsync(User user)
    {
      var canSignIn = user.IsEnabled;
    
      if (canSignIn) { 
        canSignIn = await base.CanSignInAsync(user);
      }
      return canSignIn;
    }
    

提交回复
热议问题