Why isn't [Authorize(Roles = "Admin")] working in MVC 5 RTM with ASP.NET Identity?

asp.net-identity asp.net-mvc-5 entity-framework

Question

Does [Authorize(Roles = "Admin")] work with Identity in ASP.NET out of the box in MVC 5 RTM?

No luck for me. Recall that[Authorize] and [Authorize(Users = "AdminUser")] perform flawlessly and create a connection between the AdminUser user and the Admin role by populating the AspNetUserRoles and AspNetRoles databases as I would anticipate them to be. This problem seems to be exclusive to roles.

1
14
12/13/2013 1:53:01 PM

Accepted Answer

In order for user roles to appear in the application in the typical, expected manner, the solution is the Lazy loading must be enabled in UserManager's DbContext.. My code was not quite "out of the box," as it turned out. I had made a tiny bit of customization to my DbContext. Hopefully Microsoft will avoid this integration flaw in the future by making sure the collection is loaded with something likeuserDbContext.Users.Include(o => o.Roles).SingleOrDefault(...) .

  • DO: ApplicationDbContext.Configuration.LazyLoadingEnabled = true;
  • DO NOT:ApplicationDbContext.Configuration.LazyLoadingEnabled = false;

Recall that ifApplicationDbContext.Configuration.LazyLoadingEnabled if it is not specified in your code, it defaults totrue . Therefore, omitting that line is equivalent to setting it totrue .

Etc.

Here is my best guess as to what occurs when lazy loading is disabled:Roles possession of theIdentityUser / ApplicationUser The UserManager or UserStore cannot access the item because the collection was not explicitly loaded. The code then continues as though the user has not been allocated any roles, but in reality, that collection was never loaded.

Ah, that sweet scent of quiet failure. If only the programming had generated some noise when anything didn't seem correct.

6
12/13/2013 1:49:45 PM

Popular Answer

ZZZ_tmp


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow