微软ASP.NET身份 - 具有相同名称的多个用户 [英] Microsoft ASP.NET Identity - Multiple Users with the same name

查看:122
本文介绍了微软ASP.NET身份 - 具有相同名称的多个用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想的东西很奇特的,我相信,我面临着一些问题,我希望能在这里用户在计算器上的帮助来解决。

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.

我正在写应用需要认证和注册。我选择使用 Microsoft.AspNet.Identity 。我没有用了很多过去,所以不要评判我对这个决定的。

I'm writing and application which requires authentication and registration. I've chosen to use Microsoft.AspNet.Identity. I've not used it a lot in the past, so don't judge me on this decision.

上述框架包含一个用户表,所有的注册用户拥有。

The framework mentioned above contains a users table, that holds all the registered users.

我创建了一个示例图片显示应用程序如何将工作。

I've created a sample picture to show how the application will be working.

该应用程序包含了3各部分组成:

The application consists out of 3 various components:


  1. 后端(的WebAPI)。

  2. 客户(直接使用的WebAPI)。

  3. 最终用户(使用移动应用程序 - iOS版)。

所以,我有哪些客户可以注册一个后端。有每个成员一个唯一的用户,所以没有问题就在这里。
一位顾客是一家公司在这里和最终用户是公司的客户。

So, I do have a backend on which Customers can register. There is one unique user per member, so no problem here. A customer is a company here and End Users are cliënts of the company.

您可能已经看到了问题,这是完全可能的,用户1 是在客户客户1 也在客户2

You might see the problem already, It's perfectly possible that User 1 is a cliënt at Customer 1 but also at Customer 2.

现在,客户可以邀请成员,才能使用移动应用程序。当客户这样做,最终用户就收到一封电子邮件,其中的链接活跃的自己。

Now, a customer can invite a member to use the Mobile application. When a customer does that, the end user does receive an e-mail with a link to active himself.

现在,那也没关系,只要你的用户是唯一的所有工作,但我有这是一个客户端的用户客户1 客户2 。这两种客户可以邀请同一用户,用户需要注册2次,每个客户

Now, that's all working fine as long as your users are unique, but I do have a user which is a cliënt of Customer 1 and Customer 2. Both customers can invite the same user and the user will need to register 2 times, one for each Customer.

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

In Microsoft.AspNet.Identity framework, users should be unique, which according to my situation, I'm not able to manage.

是否有可能额外的参数添加到 IdentityUser 这确保用户是独一无二的?

Is it possible to add extra parameters to the IdentityUser that make sure a user is unique?


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

  1. Create a custom class that inherits from IdentityUser and which includes an application 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
}


  • 改变了我的 IDbContext 相应:

    public class AppServerContext : IdentityDbContext<AppServerUser>, IDbContext { }
    


  • 修改呼叫正在使用的框架。

  • Modified calls that are using the framework.

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

    _userStore 当然是关类型的 IUserStore&LT; AppServerUser&GT;

    _userStore is off course of type IUserStore<AppServerUser>

    然而,当我注册一个已经采取了用户名的用户,我还是收到一条错误消息,指出用户名已被占用:

    However, when I do register a user with a username that is already taken, I still receive an error message saying that the username is already taken:

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

    我相信是一个解决方案

    我相信我需要改变的UserManager ,但我不知道这件事。
    我希望有人在这里有关于这个框架足够的知识来帮助我,因为它确实挡住了我们的应用程序的开发。

    What I do believe is a solution

    I do believe that I need to change the UserManager but I'm not sure about it. I do hope that someone here has enough knowledge about the framework to help me out because it's really blocking our application development.

    如果这是不可能的,我想也知道,也许你可以点我到另外一个框架,允许我做这件事。

    If it isn't possible, I would like to know also, and maybe you can point me to another framework that allows me to do this.

    注意:我不想写一个整体的用户管理自己,因为将要重新发明轮子

    Note: I don't want to write a whole user management myself because that will be reïnventing the wheel.

    推荐答案

    所有的第一次我理解其背后你的想法的想法,因此我会开始解释为什么,你不能够创建多个用户相同的名称。

    1st of all i understand the idea behind your thoughts, and as such i'll start to explain the "why" are you not able to create multiple users with the same name.

    具有相同名称的用户名:
    你现在遇到的问题是关系到IdentityDbContext。正如你所看到的(<一个href=\"https://aspnetidentity.$c$cplex.com/SourceControl/latest#src/Microsoft.AspNet.Identity.EntityFramework/IdentityDbContext.cs\" rel=\"nofollow\">https://aspnetidentity.$c$cplex.com/SourceControl/latest#src/Microsoft.AspNet.Identity.EntityFramework/IdentityDbContext.cs),在identityDbContext设立规则有关独立用户和角色,首先在模型创建:

    The username with the same name: The problem you encounter right now is related to the IdentityDbContext. As you can see (https://aspnetidentity.codeplex.com/SourceControl/latest#src/Microsoft.AspNet.Identity.EntityFramework/IdentityDbContext.cs), the identityDbContext sets up rules about the unique users and roles, First on model creation:

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

    其次才是验证实体:

    secondly on validate entity:

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

    的提示:
    你可以做什么来easilly克服这个问题,就是,在ApplicationDbContext您当前拥有,覆盖这两种方法来克服此验证

    The tip: What you can do to overcome this problem easilly, is, on the ApplicationDbContext that you currently have, override both these methods to overcome this validation

    警告
    如果没有验证您现在可以使用多个用户使用相同的名字,但你必须实施细则阻止你在同一个客户创建用户,使用相同的用户名。你可以做的是,并称要进行验证。

    Warning Without that validation you now can use multiple users with the same name, but you have to implement rules that stop you from creating users in the same customer, with the same username. What you can do is, adding that to the validation.

    希望帮助是宝贵的:)干杯!

    Hope the help was valuable :) Cheers!

    这篇关于微软ASP.NET身份 - 具有相同名称的多个用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆