I have an ASP.NET Core 3.0 app. I am using Role-Based Authorization. My Startup.cs looks like this.
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication().AddCookie();
services.AddAuthorization(options =>
{
options.AddPolicy("Admin", authBuilder => { authBuilder.RequireRole("Admin"); });
});
services.AddIdentity<SiteUser, IdentityRole>(x =>
{
x.Lockout.AllowedForNewUsers = true;
x.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(2);
x.Lockout.MaxFailedAccessAttempts = 3;
x.Password.RequireNonAlphanumeric = true;
x.Password.RequireUppercase = true;
}).AddEntityFrameworkStores<SiteDbContext>();
services.AddDbContext<SiteDbContext>(dbContextOptionBuilder =>
dbContextOptionBuilder.UseLoggerFactory(ConsoleFactory)
.UseSqlServer(Configuration.GetConnectionString(ConfigurationSettings.LocalDbKeyName)));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error/500");
app.UseStatusCodePagesWithReExecute("/Error/{0}");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
app.UseAuthentication();
app.UseAuthorization();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllers();
});
In my Controller class, I have appropriate Authorize attribute like so,
[Authorize(Roles = "Admin")]
public ActionResult Index()
{
var users= getSomeUsers();
return View(users);
}
There are 2 roles in the AspNetRoles Table ie. Admin, and User. However, a user account without the admin role can access the Index action method. It is allowing any authenticated user to access the page and not limiting access to a user who possesses the right role that is the Admin role. What am I missing?