标识 2.0 用户的用户角色始终为空

本文关键字:用户 标识 角色 | 更新日期: 2023-09-27 17:57:23

所以我在身份和用户角色方面遇到了问题。我继承了基类,然后添加了一些自定义字段。用户对象现在有一个人,另外两个类继承自该人(申请人和审阅者)。

我已经尝试了很多工作,在模型生成器中重新排序表的映射,删除我的自定义继承类,强制延迟加载。

对此的任何建议或帮助将不胜感激。

这是申请人上下文。

 public class ApplicantContext : IdentityDbContext<User>
        {
            public ApplicantContext()
                : base("ApplicantDbConnection")
            {
                this.Configuration.LazyLoadingEnabled = true;
            }

            public DbSet<Person> People { get; set; }
            public DbSet<Applicant> Graduates { get; set; }
            public DbSet<Reviewer> Reviewers { get; set; }

            //stop pluralising generated tables
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);
                modelBuilder.Entity<User>().ToTable("Users");
                modelBuilder.Entity<Role>().HasKey<string>(r => r.Id).ToTable("Roles");
                modelBuilder.Entity<User>().HasRequired(i => i.Person).WithMany().HasForeignKey<int>(i => i.PersonID);
                modelBuilder.Entity<User>().HasMany<UserRole>((User u) => u.UserRoles);
                modelBuilder.Entity<UserRole>().HasKey(r => new { UserId = r.UserId, RoleId = r.RoleId }).ToTable("UserRoles");
                modelBuilder.Entity<IdentityUser>()
                   .ToTable("Users");
                modelBuilder.Entity<IdentityRole>()
                    .ToTable("Roles");
                modelBuilder.Entity<IdentityUserRole>()
                    .ToTable("UserRoles");
                modelBuilder.Entity<IdentityUserClaim>()
                    .ToTable("UserClaims");
                modelBuilder.Entity<IdentityUserLogin>()
                    .ToTable("UserLogins");

            }
        }

db 初始化器。数据库方面的事情似乎都很好,但是当 我登录系统,登录成功,但是当它 重定向至"主控制器索引","索引"页使用 [授权(角色="审阅者")],这就是它失败的地方。它说 用户不具有该角色,但在数据库中,用户 ID 已配对 与用户角色表中的角色 ID 一起使用。因此,用户的角色是 零。

public class DataInitialiser : CreateDatabaseIfNotExists<ApplicantContext>
    {
        protected override void Seed(ApplicantContext context)
        {
            var manager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
            manager.Create(new IdentityRole("Reviewer"));
            manager.Create(new IdentityRole("Applicant"));
            ApplicationUserManager userManager = new ApplicationUserManager(new UserStore<User>(context));
            User user = new User
            {
                Person = new Reviewer
                {
                    FirstName = "Grant",
                    MiddleNames = "Mark",
                    Surname = "Weatherston",
                    OfficeID = 1,
                },
                Email = "test@test.com",
                UserName = "test@test.com",
                PhoneNumber = "0123456789",
            };
            userManager.Create(user, "Password123");
            userManager.AddToRole(user.Id, "Reviewer");
            context.SaveChanges();
            base.Seed(context);
        }
    }

从标识角色继承的自定义角色类。

 public class Role : IdentityRole
    {
        public Role() { }
        public Role(string name) :base(name)
        {
        }
    }

自定义用户类继承自标识用户,并添加属性 Person 。

 public class User : IdentityUser
    {
        public User() { }
        public int PersonID { get; set; }
        [ForeignKey("PersonID")]
        public virtual Person Person { get; set; }
        public virtual ICollection<UserRole> UserRoles {get;set;}
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

自定义用户角色类。

    public class UserRole : IdentityUserRole
        {
        }

自定义角色管理器。

public class ApplicationRoleManager : RoleManager<IdentityRole>
    {
        public ApplicationRoleManager(RoleStore<IdentityRole> roleStore)
            : base(roleStore)
        {
        }
    }

自定义用户管理器

public class ApplicationUserManager : UserManager<User>
    {
        public ApplicationUserManager(IUserStore<User> store)
            : base(store)
        {
        }
   }

标识 2.0 用户的用户角色始终为空

这有点过期了,但我通过在userIdentity声明之前添加以下行来解决此问题:

await manager.UpdateSecurityStampAsync(this.Id);

其中managerUserManager的实例

这会使用当前用户的 ID 重置安全标记。