Пользовательская роль пользователя Identity 2.0 всегда равна нулю

Итак, у меня проблемы с Identity и UserRoles. Я унаследовал от базовых классов, а затем добавил несколько настраиваемых полей. У пользовательского объекта теперь есть лицо, от которого наследуются два других класса (Заявитель и Рецензент).

Я так много пытался, чтобы это работало с точки зрения переупорядочения сопоставлений таблиц в построителе моделей, удаления моих пользовательских унаследованных классов, принудительной ленивой загрузки.

Мы будем очень благодарны за любые предложения или помощь по этому поводу.

Это контекст заявителя.

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



            }
        }

Инициализатор БД. Со стороны базы данных все в порядке, но когда я вхожу в систему, вход проходит успешно, однако, когда он перенаправляется на индекс домашнего контроллера, на странице индекса используется [Authorize (Roles = "Reviewer")], и именно здесь он терпит неудачу. В нем говорится, что пользователь не находится в этой роли, однако в базе данных UserId связан с RoleID в таблице UserRoles. Следовательно, роль пользователя равна нулю.

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 = "[email protected]",
                UserName = "[email protected]",
                PhoneNumber = "0123456789",
            };

            userManager.Create(user, "Password123");
            userManager.AddToRole(user.Id, "Reviewer");

            context.SaveChanges();

            base.Seed(context);
        }

    }

Класс Custom Role, наследующий от IdentityRole.

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

    }

Пользовательский класс User наследуется от идентификатора пользователя с добавлением свойства 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)
        {

        }

    }

Пользовательский UserManager

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

   }

person Gweaths    schedule 18.07.2016    source источник


Ответы (1)


Это немного поздно, но я решил эту проблему, добавив следующую строку прямо перед объявлением userIdentity:

await manager.UpdateSecurityStampAsync(this.Id);

Где manager - это экземпляр UserManager

Это сбрасывает штамп безопасности с идентификатором текущего пользователя.

person Ali Prasla    schedule 22.04.2017