I think maybe the title is a bit skewed, however, here's my question and objective. I'm developing an application using ASP.NET Core 3.1 MVC. I need to limit user access to certain areas, pages etc. This I've already done within the Startup.cs
file and adding the [Authorize]
attribute to my administration controller. However, what I cannot seem to figure out is: if an admin removes a users administration privileges while that user is logged in and they attempt to access a secured page, how do I keep them from accessing that page? I know the logical answer is probably to have the user sign out and log back in, however, that's not what is needed in this case.
File Startup.cs
(code snip)
public void ConfigureServices(IServiceCollection services)
{
//Configuration
services.Configure<HHConfig>(Configuration.GetSection("App"));
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Password.RequiredLength = 8;
options.Password.RequiredUniqueChars = 1;
options.SignIn.RequireConfirmedAccount = true;
})
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddControllersWithViews();
services.AddRazorPages(options => {
options.Conventions.AuthorizeFolder("/Administration");
});
services.AddMvc().AddRazorPagesOptions(options =>
{
options.Conventions.AddAreaPageRoute("Identity", "/Account/Login", "/Account/Login");
});
//Transient and Scoped Services Here
services.AddTransient<ApplicationDbContext>();
services.AddScoped<IEmailManager, EmailManager>();
}
Administration Controller
[Authorize(Roles = "Admin")]
public class AdministrationController : Controller
{
private readonly RoleManager<IdentityRole> roleManager;
private readonly UserManager<ApplicationUser> userManager;
private SignInManager<ApplicationUser> signInManager { get; }
private readonly IEmailManager emailManager;
public AdministrationController(RoleManager<IdentityRole> roleManager,UserManager<ApplicationUser> userManager,SignInManager<ApplicationUser> signInManager, IEmailManager emailMgr)
{
this.roleManager = roleManager;
this.userManager = userManager;
this.signInManager = signInManager;
emailManager = emailMgr;
}
}