I have a controller method that is only allowed to be used by users with the canModify role. I have made sure that the user has this role, and that the user is displayed as being a member of this role group. But when I try to edit a post on this account, it displays the "Access Denied" page.
I am not sure where to go from here. I have printed out the roles belonging to the currently logged in user, and it displays "canModify". I have printed out the list of users who possess the role "canModify", and the user I am logged in as is printed out.
GET Edit method in the Controller:
[Authorize(Roles = "canModify")]
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var post = await _context.Post.FindAsync(id);
if (post == null)
{
return NotFound();
}
return View(post);
}
Where the role is set:
private async Task Admin(UserManager<ApplicationUser> userManager, ApplicationDbContext context)
{
await rm.CreateAsync(new IdentityRole("canModify"));
ApplicationUser admin = new ApplicationUser
{
UserName = "admin@test.com"
};
if (context.Users.Where(u => u.UserName == admin.UserName).Count() == 0)
{
userManager.CreateAsync(admin, "Password123!").Wait();
userManager.AddToRoleAsync(admin, "canModify").Wait();
}
}
This is my Configure method in Startup.cs:
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
var scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
var scope = scopeFactory.CreateScope();
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
DbInitializer dbi = new DbInitializer(roleManager);
dbi.Initialize(context, userManager);
It should be the case now that the admin can edit the posts in the system, but it says access denied.