I wrote a small ASP.NET Core 8 application with Microsoft identity authentication to login. Now I noticed that my JS files are not protected for anonymously access so I read about static files (https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-8.0).
My issue I have now is that I still would like to grant access anonymously when I am in debugging mode.
For the controller authentication I use:
app.MapControllers()
.WithMetadata(new AllowAnonymousAttribute());
But I'm trying to do the same with static files I still get no access:
app.MapFallbackToFile("/StaticFiles/{*filepath}")
.WithMetadata(new AllowAnonymousAttribute());
I also tried /StaticFiles/*
or /StaticFiles/**/*
.
The static file function is:
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
});
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(builder.Environment.ContentRootPath, staticFiles)),
RequestPath = "/StaticFiles"
});
Is this even the correct way to protect my JS files, and what may be the issue?
Thanks
You misunderstood the useage of app.MapFallbackToFile
middleware,it is intended to handle cases where URL path of the request does not contain a file name, and no other endpoint has matched. This is convenient for routing requests for dynamic content to a SPA framework, while also allowing requests for non-existent files to result in an HTTP 404.
Also,if there's only one parameter inside MapFallbackToFile()
method,the parameter should be a certain file path instead of route partten:"/StaticFiles/{*filepath}"
My issue I have now is that I still would like to grant access anonymously when I am in debugging mode.
you may try as below so that the static files would be accessed anonymously only in debugging
if (app.Environment.IsDevelopment())
{
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(builder.Environment.ContentRootPath, staticFiles)),
RequestPath = "/StaticFiles"
});
}
app.UseAuthorization();
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(builder.Environment.ContentRootPath, staticFiles)),
RequestPath = "/StaticFiles"
});