Microsoft ASP.NET Identity - Multiple Users with the same name

后端 未结 2 757
面向向阳花
面向向阳花 2020-12-15 12:11

I\'m trying something quite exotic I believe and I\'m facing a few problems, which I hope can be solved with the help of the users here on StackOverflow.

The story<

2条回答
  •  情话喂你
    2020-12-15 12:39

    May be someone can find this helpful. In our project we use ASP.NET identity 2 and some day we came across case where two users have identical names. We use emails as logins in our app and they, indeed, have to be unique. But we don't want to have user names unique anyway. What we did just customized few classes of identity framework as follows:

    1. Changed our AppIdentityDbContext by creating index on UserName field as non-unique and override ValidateEntity in tricky way. And then using migrations update database. Code looks like:

      public class AppIdentityDbContext : IdentityDbContext
      {
      
      public AppIdentityDbContext()
          : base("IdentityContext", throwIfV1Schema: false)
      {
      }
      
      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
          base.OnModelCreating(modelBuilder); // This needs to go before the other rules!
      
           *****[skipped some other code]*****
      
          // In order to support multiple user names 
          // I replaced unique index of UserNameIndex to non-unique
          modelBuilder
          .Entity()
          .Property(c => c.UserName)
          .HasColumnAnnotation(
              "Index", 
              new IndexAnnotation(
              new IndexAttribute("UserNameIndex")
              {
                  IsUnique = false
              }));
      
          modelBuilder
              .Entity()
              .Property(c => c.Email)
              .IsRequired()
              .HasColumnAnnotation(
                  "Index",
                  new IndexAnnotation(new[]
                  {
                      new IndexAttribute("EmailIndex") {IsUnique = true}
                  }));
      }
      
      /// 
      ///     Override 'ValidateEntity' to support multiple users with the same name
      /// 
      /// 
      /// 
      /// 
      protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry,
          IDictionary items)
      {
          // call validate and check results 
          var result = base.ValidateEntity(entityEntry, items);
      
          if (result.ValidationErrors.Any(err => err.PropertyName.Equals("User")))
          {
              // Yes I know! Next code looks not good, because I rely on internal messages of Identity 2, but I should track here only error message instead of rewriting the whole IdentityDbContext
      
              var duplicateUserNameError = 
                  result.ValidationErrors
                  .FirstOrDefault(
                  err =>  
                      Regex.IsMatch(
                          err.ErrorMessage,
                          @"Name\s+(.+)is\s+already\s+taken",
                          RegexOptions.IgnoreCase));
      
              if (null != duplicateUserNameError)
              {
                  result.ValidationErrors.Remove(duplicateUserNameError);
              }
          }
      
          return result;
      }
      }
      
    2. Create custom class of IIdentityValidator interface and set it to our UserManager.UserValidator property:

      public class AppUserValidator : IIdentityValidator
      {
      /// 
      ///     Constructor
      /// 
      /// 
      public AppUserValidator(UserManager manager)
      {
          Manager = manager;
      }
      
      private UserManager Manager { get; set; }
      
      /// 
      ///     Validates a user before saving
      /// 
      /// 
      /// 
      public virtual async Task ValidateAsync(AppUser item)
      {
          if (item == null)
          {
              throw new ArgumentNullException("item");
          }
      
          var errors = new List();
      
          ValidateUserName(item, errors);
          await ValidateEmailAsync(item, errors);
      
          if (errors.Count > 0)
          {
              return IdentityResult.Failed(errors.ToArray());
          }
          return IdentityResult.Success;
      }
      
      private void ValidateUserName(AppUser user, List errors)
      {
          if (string.IsNullOrWhiteSpace(user.UserName))
          {
              errors.Add("Name cannot be null or empty.");
          }
          else if (!Regex.IsMatch(user.UserName, @"^[A-Za-z0-9@_\.]+$"))
          {
              // If any characters are not letters or digits, its an illegal user name
              errors.Add(string.Format("User name {0} is invalid, can only contain letters or digits.", user.UserName));
          }
      }
      
      // make sure email is not empty, valid, and unique
      private async Task ValidateEmailAsync(AppUser user, List errors)
      {
          var email = user.Email;
      
          if (string.IsNullOrWhiteSpace(email))
          {
              errors.Add(string.Format("{0} cannot be null or empty.", "Email"));
              return;
          }
          try
          {
              var m = new MailAddress(email);
          }
          catch (FormatException)
          {
              errors.Add(string.Format("Email '{0}' is invalid", email));
              return;
          }
          var owner = await Manager.FindByEmailAsync(email);
          if (owner != null && !owner.Id.Equals(user.Id))
          {
              errors.Add(string.Format(CultureInfo.CurrentCulture, "Email '{0}' is already taken.", email));
          }
      }
      }
      
      public class AppUserManager : UserManager
      {
      public AppUserManager(
          IUserStore store,
          IDataProtectionProvider dataProtectionProvider,
          IIdentityMessageService emailService)
          : base(store)
      {
      
          // Configure validation logic for usernames
          UserValidator = new AppUserValidator(this);
      
    3. And last step is change AppSignInManager. Because now our user names is not unique we use email to log in:

      public class AppSignInManager : SignInManager
      {
       ....
      public virtual async Task PasswordSignInViaEmailAsync(string userEmail, string password, bool isPersistent, bool shouldLockout)
      {
          var userManager = ((AppUserManager) UserManager);
          if (userManager == null)
          {
              return SignInStatus.Failure;
          }
      
          var user = await UserManager.FindByEmailAsync(userEmail);
          if (user == null)
          {
              return SignInStatus.Failure;
          }
      
          if (await UserManager.IsLockedOutAsync(user.Id))
          {
              return SignInStatus.LockedOut;
          }
      
          if (await UserManager.CheckPasswordAsync(user, password))
          {
              await UserManager.ResetAccessFailedCountAsync(user.Id);
              await SignInAsync(user, isPersistent, false);
              return SignInStatus.Success;
          }
      
          if (shouldLockout)
          {
              // If lockout is requested, increment access failed count which might lock out the user
              await UserManager.AccessFailedAsync(user.Id);
              if (await UserManager.IsLockedOutAsync(user.Id))
              {
                  return SignInStatus.LockedOut;
              }
          }
          return SignInStatus.Failure;
      }
      

      And now code looks like:

      [HttpPost]
      [AllowAnonymous]
      [ValidateAntiForgeryToken]
      public async Task Index(User model, string returnUrl)
      {
          if (!ModelState.IsValid)
          {
              return View(model);
          }
          var result = 
              await signInManager.PasswordSignInViaEmailAsync(
                  model.Email,
                  model.Password, 
                  model.StaySignedIn,
                  true);
      
          var errorMessage = string.Empty;
          switch (result)
          {
              case SignInStatus.Success:
                  if (IsLocalValidUrl(returnUrl))
                  {
                      return Redirect(returnUrl);
                  }
      
                  return RedirectToAction("Index", "Home");
              case SignInStatus.Failure:
                  errorMessage = Messages.LoginController_Index_AuthorizationError;
                  break;
              case SignInStatus.LockedOut:
                  errorMessage = Messages.LoginController_Index_LockoutError;
                  break;
              case SignInStatus.RequiresVerification:
                  throw new NotImplementedException();
          }
      
          ModelState.AddModelError(string.Empty, errorMessage);
          return View(model);
      }
      

    P.S. I don't really like how I override ValidateEntity method. But I decided to do this because instead I have to implement DbContext class almost identical to IdentityDbContext, thus I have to track changes on it when update identity framework package in my project.

提交回复
热议问题