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

前端 未结 3 1243
没有蜡笔的小新
没有蜡笔的小新 2020-12-28 19:36

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

I\'ve had no luck. Note that [Authorize] and

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-28 19:43

    And the answer is the UserManager's DbContext must have lazy loading enabled in order for user roles to manifest in the application in the usual, expected, way. As it turns out, not all of my code was "out of the box." I had customized my DbContext ever so slightly. Hopefully in the future Microsoft will sidestep this integration bug by ensuring the collection is loaded with something like userDbContext.Users.Include(o => o.Roles).SingleOrDefault(...).

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

    Note that if ApplicationDbContext.Configuration.LazyLoadingEnabled is not set in your code then it defaults to true. So leaving off that line is as good as setting it to true.

    Etc.

    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.

    Ah, the aroma of silent failure. Had the code only made some noise when things didn't look right.

提交回复
热议问题