Home > Back-end >  How do I exclude static files from ASP.NET Core's authorization fallback policy
How do I exclude static files from ASP.NET Core's authorization fallback policy

Time:09-21

I am currently developing an application where I have set up an authorization fallback policy to avoid having to set a policy on each controller individually. The problem is that you now have to be logged in to access the static files under "wwwroot" (where my frontend is) which is obviously wrong, since you need the frontend to be able login at all.

Is there a way to use the fallback policy but exclude the static files from it (e.g. somehow add AllowAnonymous to it)? Or am I on the wrong track and should solve this differently?

Edit: Accessing the static files directly (https://localhost:5001/index.html) works, but I am getting a 401 error when I call the root url (https://localhost:5001) and MapFallbackToFile("index.html"). Everything works fine if I comment out the fallback policy.

Here is my current Startup.cs (I am trying out .NET 6)

Authorization Service:

builder.Services.AddAuthorization(options =>
{
    options.FallbackPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .RequireRole(Roles.User)
        .Build();
});

Middleware:

var app = builder.Build();

// Configure the HTTP request pipeline.

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Web v1"));
}
else
{
    app.UseHsts();
}

app.UseHealthChecks("/health");

app.UseHangfireDashboard();

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();

app.UseAuthorization();

app.UseMiddleware<UserMiddleware>();

app.UseResponseCompression();

app.MapControllers();

app.MapFallbackToFile("index.html");

app.Run();

CodePudding user response:

To have the auth only hit razor pages and controllers, and leaving your other files alone, this should accomplish that:

services.AddRazorPages().AddMvcOptions(options => 
                options.Filters.Add(new AuthorizeFilter("MyCustomPolicy"))
);
  • Related