I added a fallback policy to my asp.net core application because I wanted to require a specific role as the fallback instead of just blanket authorization.
However, now pages that have the AllowAnonymous attribute are using my fallback policy, which seems to directly contradict documentation. Microsoft docs say that the fallback policy is for pages without any authorize or AllowAnonymous attribute.
For example, Razor Pages, controllers, or action methods with
[AllowAnonymous]or[Authorize(PolicyName="MyPolicy")]use the applied authentication attribute rather than the fallback authentication policy.
https://docs.microsoft.com/en-us/aspnet/core/security/authorization/secure-data?view=aspnetcore-6.0
I'm wondering if perhaps my configuration in Startup is wrong, but searching I've found nothing similar to my issue.
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyDbContext")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<MyDbContext>();
services.AddScoped<MySharedService>();
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = $"/Identity/Account/Login";
options.LogoutPath = $"/Identity/Account/Logout";
options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
});
services.AddAuthorization(options =>
{
options.AddPolicy("IsSystemAdmin", policy => policy.RequireRole("SystemAdmin"));
options.FallbackPolicy = options.GetPolicy("IsSystemAdmin");
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}