Monday, October 15, 2018

Having Issues With Roles In Asp.Net MVC

If I use

services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>(); 

in my Startup.cs then

[Authorize(Roles = "Administrator")] 

in my controllers always causes an "Access Denied" Error. (Code for seeding admin will be at bottom)

If I use

services.AddIdentity<IdentityUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>(); 

I can't take advantage of MC's login/ register, and I'm not sure how to handle that on my own. Still working on that.

My DbInitialize.cs file is running, and I have the following within it

 private static async Task EnsureRolesAsync( RoleManager<IdentityRole> roleManager) { var alreadyExists = await roleManager .RoleExistsAsync(Constants.AdministratorRole); if (alreadyExists) return; await roleManager.CreateAsync( new IdentityRole(Constants.AdministratorRole)); } private static async Task EnsureTestAdminAsync( UserManager<IdentityUser> userManager) { var testAdmin = await userManager.Users .Where(x => x.UserName == "amber@tootmail.com") .SingleOrDefaultAsync(); if (testAdmin != null) return; testAdmin = new IdentityUser { UserName = "amber@tootmail.com", Email = "amber@tootmail.com" }; await userManager.CreateAsync( testAdmin, "R@m0n@"); await userManager.AddToRoleAsync( testAdmin, Constants.AdministratorRole); } 

And both the Admin and the Role are being added and are present in my db.

Having Issues With Roles In Asp.Net MVC Click here
  • Blogger Comment
  • Facebook Comment

0 comments:

Post a Comment

The webdev Team