In .NET 9 MapStaticAssets was introduced to replace UseStaticFiles. The documentation here advises the following...
The ASP.NET Core templates call MapStaticAssets before calling UseAuthorization. Most apps follow this pattern. When the Static File Middleware is called before the authorization middleware:
No authorization checks are performed on the static files.
Static files served by the Static File Middleware, such as those under wwwroot, are publicly accessible.
However this does not seem to be the case. Even the project template fails as shown below. The issue seems to arise from this setup.
builder.Services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the default policy.
options.FallbackPolicy = options.DefaultPolicy;
});
But based on the middleware setup and the documentation the public assets should not be getting authenticated. Is this a bug or is it setup wrong?
var builder = WebApplication.CreateBuilder(args);
var settings = builder.Configuration.GetSection("AzureAd");
var initialScopes = builder.Configuration["MicrosoftGraph:Scopes"]?.Split(' ');
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(settings)
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddInMemoryTokenCaches();
builder.Services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the default policy.
options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddRazorPages()
.AddMicrosoftIdentityUI();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
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.MapStaticAssets();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages()
.WithStaticAssets();
app.MapControllers();
app.Run();
After signing out the SignedOut page is not rendered correctly and if you try to access one of the public assets directly in another tab such as localhost:7119/css/site.css then you are forced to authenticate again. Therefore the MapStaticAssets feature seems to break anonymous pages.