【问题标题】:Microsoft ASP.NET Identity - Multiple Users with the same nameMicrosoft ASP.NET 身份 - 具有相同名称的多个用户
【发布时间】:2015-04-14 13:36:21
【问题描述】:

我正在尝试一些非常奇特的东西,我相信我正面临一些问题,我希望可以在 StackOverflow 上的用户的帮助下解决这些问题。

故事

我正在编写需要身份验证和注册的应用程序。我选择使用Microsoft.AspNet.Identity。我过去没有经常使用它,所以请不要以此决定评判我。

上面提到的框架包含一个 users 表,其中包含所有注册用户。

我创建了一张示例图片来展示应用程序的工作方式。

该应用程序由 3 个不同的组件组成:

  1. 后端 (WebAPI)。
  2. 客户(直接使用 WebAPI)。
  3. 最终用户(使用移动应用 - iOS)。

所以,我确实有一个客户可以注册的后端。每个成员有一个唯一用户,所以这里没有问题。 此处的客户是一家公司,而最终用户是该公司的客户。

您可能已经看到了问题,User 1 很可能是Customer 1 的客户,但也可能是Customer 2 的客户。

现在,客户可以邀请会员使用移动应用程序。当客户这样做时,最终用户确实会收到一封电子邮件,其中包含指向活动自己的链接。

现在,只要您的用户是唯一的,这一切都可以正常工作,但我确实有一个用户是 Customer 1Customer 2 的客户。两个客户都可以邀请同一个用户,用户需要注册2次,每个Customer一个。

问题

Microsoft.AspNet.Identity框架中,用户应该是唯一的,根据我的情况,我无法管理。

问题

是否可以向IdentityUser 添加额外参数以确保用户是唯一的?

我已经做了什么

  1. 创建一个继承自 IdentityUser 并包含应用程序 ID 的自定义类:

    public class AppServerUser : IdentityUser
    {
        #region Properties
    
        /// <summary>
        ///     Gets or sets the id of the member that this user belongs to.
        /// </summary>
        public int MemberId { get; set; }
    
        #endregion
    }
    
  2. 相应地更改了我的IDbContext

    public class AppServerContext : IdentityDbContext<AppServerUser>, IDbContext { }
    
  3. 使用框架的修改调用。

    IUserStore<IdentityUser> -> IUserStore<AppServerUser>
    UserManager<IdentityUser>(_userStore) -> UserManager<AppServerUser>(_userStore);
    

    _userStore 偏离IUserStore&lt;AppServerUser&gt; 类型

但是,当我使用已被占用的用户名注册用户时,我仍然会收到一条错误消息,指出该用户名已被占用:

var result = await userManager.CreateAsync(new AppServerUser {UserName = "testing"}, "testing");

我确实认为是一个解决方案

我确实认为我需要更改UserManager,但我不确定。 我确实希望这里有人对框架有足够的了解来帮助我,因为它确实阻碍了我们的应用程序开发。

如果不可能,我也想知道,也许您可​​以向我指出另一个允许我这样做的框架。

注意:我不想自己编写一个完整的用户管理,因为那样会重新发明轮子。

【问题讨论】:

  • 仅供参考,这称为“多租户”。这是网站中的一个常见概念,也是一个众所周知的问题。您会在此处使用 Identity Framework 找到很多关于此的问题。
  • 我不清楚您是要为每个客户/用户单独记录不同的记录,还是要为多个客户提供一个用户。
  • 用户表中需要有 2 条用户记录,但两条记录的用户名和密码相同。将有另一个字段唯一标识一条记录。
  • 您可能会发现这很有用stackoverflow.com/questions/20037145/…
  • @ErikFunkenbusch 感谢您提供非常有用的帖子。

标签: c# asp.net authentication forms-authentication asp.net-identity


【解决方案1】:

可能有人会觉得这很有帮助。在我们的项目中,我们使用 ASP.NET 标识 2,有一天我们遇到了两个用户具有相同名称的情况。我们在我们的应用程序中使用电子邮件作为登录名,它们确实必须是唯一的。但是我们不希望用户名是唯一的。我们所做的只是定制了几类身份框架如下:

  1. 通过在 UserName 字段上创建索引为非唯一并以棘手的方式覆盖 ValidateEntity 来更改我们的 AppIdentityDbContext。然后使用迁移更新数据库。代码如下:

    public class AppIdentityDbContext : IdentityDbContext<AppUser>
    {
    
    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<AppUser>()
        .Property(c => c.UserName)
        .HasColumnAnnotation(
            "Index", 
            new IndexAnnotation(
            new IndexAttribute("UserNameIndex")
            {
                IsUnique = false
            }));
    
        modelBuilder
            .Entity<AppUser>()
            .Property(c => c.Email)
            .IsRequired()
            .HasColumnAnnotation(
                "Index",
                new IndexAnnotation(new[]
                {
                    new IndexAttribute("EmailIndex") {IsUnique = true}
                }));
    }
    
    /// <summary>
    ///     Override 'ValidateEntity' to support multiple users with the same name
    /// </summary>
    /// <param name="entityEntry"></param>
    /// <param name="items"></param>
    /// <returns></returns>
    protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry,
        IDictionary<object, object> 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. 创建IIdentityValidator&lt;AppUser&gt;接口的自定义类并将其设置为我们的UserManager&lt;AppUser&gt;.UserValidator属性:

    public class AppUserValidator : IIdentityValidator<AppUser>
    {
    /// <summary>
    ///     Constructor
    /// </summary>
    /// <param name="manager"></param>
    public AppUserValidator(UserManager<AppUser> manager)
    {
        Manager = manager;
    }
    
    private UserManager<AppUser, string> Manager { get; set; }
    
    /// <summary>
    ///     Validates a user before saving
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    public virtual async Task<IdentityResult> ValidateAsync(AppUser item)
    {
        if (item == null)
        {
            throw new ArgumentNullException("item");
        }
    
        var errors = new List<string>();
    
        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<string> 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<string> 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<AppUser>
    {
    public AppUserManager(
        IUserStore<AppUser> store,
        IDataProtectionProvider dataProtectionProvider,
        IIdentityMessageService emailService)
        : base(store)
    {
    
        // Configure validation logic for usernames
        UserValidator = new AppUserValidator(this);
    
  3. 最后一步是更改AppSignInManager。因为现在我们的用户名不是唯一的,所以我们使用电子邮件登录:

    public class AppSignInManager : SignInManager<AppUser, string>
    {
     ....
    public virtual async Task<SignInStatus> 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;
    }
    

    现在代码如下:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> 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);
    }
    

附:我真的不喜欢我如何覆盖ValidateEntity 方法。但我决定这样做是因为我必须实现与IdentityDbContext 几乎相同的 DbContext 类,因此在我的项目中更新身份框架包时我必须跟踪它的更改。

【讨论】:

    【解决方案2】:

    首先我理解您的想法背后的想法,因此我将开始解释“为什么”您不能创建多个具有相同名称的用户。

    同名用户名: 您现在遇到的问题与 IdentityDbContext 有关。如您所见 (https://aspnetidentity.codeplex.com/SourceControl/latest#src/Microsoft.AspNet.Identity.EntityFramework/IdentityDbContext.cs),identityDbContext 设置了有关唯一用户和角色的规则,首先是模型创建:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            if (modelBuilder == null)
            {
                throw new ArgumentNullException("modelBuilder");
            }
    
            // Needed to ensure subclasses share the same table
            var user = modelBuilder.Entity<TUser>()
                .ToTable("AspNetUsers");
            user.HasMany(u => u.Roles).WithRequired().HasForeignKey(ur => ur.UserId);
            user.HasMany(u => u.Claims).WithRequired().HasForeignKey(uc => uc.UserId);
            user.HasMany(u => u.Logins).WithRequired().HasForeignKey(ul => ul.UserId);
            user.Property(u => u.UserName)
                .IsRequired()
                .HasMaxLength(256)
                .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("UserNameIndex") { IsUnique = true }));
    
            // CONSIDER: u.Email is Required if set on options?
            user.Property(u => u.Email).HasMaxLength(256);
    
            modelBuilder.Entity<TUserRole>()
                .HasKey(r => new { r.UserId, r.RoleId })
                .ToTable("AspNetUserRoles");
    
            modelBuilder.Entity<TUserLogin>()
                .HasKey(l => new { l.LoginProvider, l.ProviderKey, l.UserId })
                .ToTable("AspNetUserLogins");
    
            modelBuilder.Entity<TUserClaim>()
                .ToTable("AspNetUserClaims");
    
            var role = modelBuilder.Entity<TRole>()
                .ToTable("AspNetRoles");
            role.Property(r => r.Name)
                .IsRequired()
                .HasMaxLength(256)
                .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("RoleNameIndex") { IsUnique = true }));
            role.HasMany(r => r.Users).WithRequired().HasForeignKey(ur => ur.RoleId);
        }
    

    其次是验证实体:

    protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry,
            IDictionary<object, object> items)
        {
            if (entityEntry != null && entityEntry.State == EntityState.Added)
            {
                var errors = new List<DbValidationError>();
                var user = entityEntry.Entity as TUser;
                //check for uniqueness of user name and email
                if (user != null)
                {
                    if (Users.Any(u => String.Equals(u.UserName, user.UserName)))
                    {
                        errors.Add(new DbValidationError("User",
                            String.Format(CultureInfo.CurrentCulture, IdentityResources.DuplicateUserName, user.UserName)));
                    }
                    if (RequireUniqueEmail && Users.Any(u => String.Equals(u.Email, user.Email)))
                    {
                        errors.Add(new DbValidationError("User",
                            String.Format(CultureInfo.CurrentCulture, IdentityResources.DuplicateEmail, user.Email)));
                    }
                }
                else
                {
                    var role = entityEntry.Entity as TRole;
                    //check for uniqueness of role name
                    if (role != null && Roles.Any(r => String.Equals(r.Name, role.Name)))
                    {
                        errors.Add(new DbValidationError("Role",
                            String.Format(CultureInfo.CurrentCulture, IdentityResources.RoleAlreadyExists, role.Name)));
                    }
                }
                if (errors.Any())
                {
                    return new DbEntityValidationResult(entityEntry, errors);
                }
            }
            return base.ValidateEntity(entityEntry, items);
        }
    }
    

    提示: 你可以做些什么来轻松克服这个问题,在你当前拥有的 ApplicationDbContext 上,重写这两个方法来克服这个验证

    警告 如果没有该验证,您现在可以使用多个具有相同名称的用户,但您必须实施阻止您在同一客户中创建具有相同用户名的用户的规则。您可以做的是,将其添加到验证中。

    希望帮助是有价值的 :) 干杯!

    【讨论】:

    • 感谢您的回答,这正是我想要的。只有一个问题:我应该在OnModelCreating 方法中更改什么,因为不清楚该方法设置了什么验证。
    • 如您所见,在创建表时,用户名被设置为唯一:".HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("UserNameIndex") { IsUnique = true })) ;"你应该删除这个唯一性;)
    • 好的,在深入挖掘之后,还有一个问题:另外,ValidateEntity 方法确实调用了我无法调用的base.ValidateEntity,因为这会导致调用IdentityContext 验证方法,如果我有多个用户,这将失败。但是不调用基类会导致其他属性不被验证,比如属性被标记为RequiredAttribute
    • 出于手头的目的,由于您只处理来自 identity2 的验证,因此您可以替换该调用以返回 new DbEntityValidationResult(entityEntry, new List());
    • 我不太明白你最近的评论,你的意思是替换base.Validate()?我认为这不会触发数据注释属性。我觉得应该有更好的解决方案然后调整代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 2016-02-04
    相关资源
    最近更新 更多