Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.net MVC + ASP.net Identity Seeding roles and users

In Migrations Configuration class, there is Seed method, and it looks like:

protected override void Seed(DatabaseContext context)
        {
           var  roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
           var  userManager = new UserManager<User>(new UserStore<User>(context)); 

            if (!roleManager.RoleExists("Administrator"))
            {
                roleManager.Create(new IdentityRole("Administrator"));
            }

            var user = new User {UserName = "someUserName"};


            if (userManager.FindByName("someUserName") == null)
            {
                var result = userManager.Create(user, "password");

                if (result.Succeeded)
                {
                    userManager.AddToRole(user.Id, "Administrator");
                }    

            }
            }

And then in PM console I've run update-database, and it successfully seeded database, and in table AspNetUserRoles I can see that user someUserName and Administrator role are connected.

But when I put attribute [Authorize(Roles = "Administrator")] above controller I've been redirected to log in page as if my user wasn't in that role, so I've added line in my controller:

var x = _userManager.IsInRole(_userManager.FindByName("someUserName").Id, "Administrator");

And x is false. Why is this happening ? And how can I fix it ? And if this isn't proper way to seed database, which is ?

like image 385
hyperN Avatar asked Dec 09 '13 12:12

hyperN


1 Answers

Try in your seed method

 context.Configuration.LazyLoadingEnabled = true;

Here's my guess at what is going on when lazy loading is disabled, the Roles property of the IdentityUser / ApplicationUser object is null or empty when the UserManager or UserStore accesses it because that collection was not manually loaded. The code then carries on like no roles have been assigned to the user when in fact that collection simply was never loaded.

like image 153
Nilesh Gajare Avatar answered Nov 15 '22 09:11

Nilesh Gajare