Reputation: 90
I am trying to add an administrator role to my ASPDotNet Core project using Identity and Entity Frame Work. The goal is to give admin's access to views/controllers that will allow them to make changes to the website that normal users wont have access to.
Here is the code I use to create the roles, super user, and seed the data base (later I might make a seed database class, but I'm focusing on getting the basics to work first). This code lives in my startup class at the moment. CreateSuperUser is called in the configure method.
private async Task CreateSuperUser(IServiceProvider serviceProvider)
{
var _roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var _userManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();
IdentityResult result;
var doesAdminRoleExist = await _roleManager.RoleExistsAsync("AdminRole");
var doesBasicRoleExist = await _roleManager.RoleExistsAsync("BasicRole");
if (!doesAdminRoleExist)
{
IdentityRole AdminRole = new IdentityRole("AdminRole");
result = await _roleManager.CreateAsync(AdminRole);
IdentityUser SuperUser = new IdentityUser() { Email = "[email protected]", PasswordHash = "SecureP@ssword!1234", UserName = "[email protected]", };
var createSuperUser = await _userManager.CreateAsync(SuperUser, SuperUser.PasswordHash);
if (createSuperUser.Succeeded)
{
await _userManager.AddToRoleAsync(SuperUser, AdminRole.Name);
}
}
if (!doesBasicRoleExist)
{
IdentityRole BasicRole = new IdentityRole("BasicRole");
result = await _roleManager.CreateAsync(BasicRole);
}
}
In my Controller class I request authorization like this
[Authorize(Roles = "AdminRole")]
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
I am able to sign in no problem with [email protected], but when I try to click on the contact link it tells me I do not have access to this resource. I simply cannot figure out how to get this custom role created correctly. My specific question is: Can someone please help me locate the mistake in my process that is preventing me from authorizing by role.
I have spent a lot of time reading stack overflow, google, and the Microsoft documentation, so please don't suggest that. My method is based very much off one of the answers to an other user on here, and the Microsoft docs are a PDF on my desktop.
I am newer to programming and am having trouble grasping it all. Especially with the differences in 2.0 and 2.1. Not to mention Framework 4.6 in the mix.
I apologize for the long post. Thank you in advance for your help.
On a side note, here are my configure methods just in case they help. I have also ran add-migration/update-database from nuget's console.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddAuthentication();
services.AddAuthorization();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env,IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
CreateSuperUser(serviceProvider).Wait();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
Upvotes: 2
Views: 1098
Reputation: 30016
This is a bug which is tracked UserRoles in DefaultIdentity #1813.
For a work around, change your code like below
//services.AddDefaultIdentity<IdentityUser>()
// .AddEntityFrameworkStores<ApplicationDbContext>();
//services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>()
// .AddEntityFrameworkStores<ApplicationDbContext>()
// ;
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultUI()
.AddDefaultTokenProviders();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
This issue is fixed in release/2.2
which is tracked Fix issue with role claim missing in AddIdentityCore #1832.
Note, if above code not work for you, you may need to logout and login since this Identity is saved by Cookies
.
Upvotes: 1