skip to content

On an ASP.NET Core 10 cycling-club site, how would you serve a members-only downloads folder so that anonymous visitors cannot fetch its files?

level: seniorimportance: should knowfreq 45%

answer

  1. static file middleware never checks authorization
  2. keep the folder outside wwwroot
  3. AuthorizationOptions.FallbackPolicy
  4. UseStaticFiles after UseAuthorization
  5. TypedResults.PhysicalFile plus RequireAuthorization

basics

~10 s

Keep the files outside wwwroot, then either serve them with a second UseStaticFiles placed after UseAuthorization under a fallback policy requiring authenticated users, or through an endpoint with RequireAuthorization that returns TypedResults.PhysicalFile.

solid answer

~40 s

The static file middleware performs no authorization check, so anything it serves before `UseAuthorization` is public, and a guessable path in `wwwroot` is public too. Move the downloads to a folder under the content root. One option is to set `AuthorizationOptions.FallbackPolicy` to require an authenticated user, call `UseAuthentication()` and `UseAuthorization()` explicitly, and then add `UseStaticFiles` with a `PhysicalFileProvider` for that folder and `RequestPath = "/downloads"`. No endpoint matches those requests, so the authorization middleware applies the fallback policy and challenges anonymous users. The fallback policy then covers every request without authorization metadata that reaches `UseAuthorization`, so public files must be served before it and `MapStaticAssets` endpoints need `AllowAnonymous`. The more controllable option is an endpoint, `MapGet("/downloads/{fileName}")` with `RequireAuthorization("Members")`, that validates the name and returns `TypedResults.PhysicalFile`.

code

csharp · 24 lines
csharp
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.FileProviders;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication().AddCookie();
builder.Services.AddAuthorization(o =>
    o.FallbackPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser().Build());
var app = builder.Build();

app.UseStaticFiles();            // public wwwroot, before authorization
app.UseAuthentication();
app.UseAuthorization();

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(
        Path.Combine(builder.Environment.ContentRootPath, "member-downloads")),
    RequestPath = "/downloads",
    OnPrepareResponse = ctx =>
        ctx.Context.Response.Headers.CacheControl = "private, no-store"
});

app.Run();

go deeper

for a junior

Know that files in wwwroot are public to anyone with the URL and that protected files belong in a folder outside it.

for a middle

Explain why static files skip authorization, how the fallback policy applies to requests with no endpoint, and how an authorized endpoint returns a file.

for a senior

Choose between the fallback-policy and endpoint designs, foresee the fallback policy catching public assets, and guard the endpoint against path traversal.

for a principal

Decide whether member content should be served by the app at all or moved to storage with short-lived signed links, weighing control against load.

## Why wwwroot is the wrong place `StaticFileMiddleware` checks the method, the path, the extension and whether the file exists. It never consults the user or any `[Authorize]` metadata. In the usual layout it runs before `UseAuthorization`, so every file under the web root is served to anyone who knows its URL. Attributes on controllers protect those controllers, not files. Random-looking names are not protection either: links get shared, they appear in browser history and proxy logs, and nothing revokes access to a file once a member leaves the club. The first step is the same for every design: **move the members' files out of the web root**, for example to `{content root}/member-downloads`. Then pick how they are served. ## Option 1: a second static file middleware behind the fallback policy 1. Register a **fallback policy** that requires an authenticated user: ```csharp builder.Services.AddAuthorization(o => o.FallbackPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser().Build()); ``` 2. In the pipeline, serve public files first, then call `UseAuthentication()` and `UseAuthorization()` explicitly, then add a `UseStaticFiles` whose `FileProvider` is a `PhysicalFileProvider` over the members' folder and whose `RequestPath` is `/downloads`. Why it works: a request for `/downloads/route-book.pdf` matches no endpoint. `AuthorizationMiddleware` combines the endpoint's authorization data, finds none, and falls back to `FallbackPolicy`; an anonymous user is challenged before the second static file middleware runs. What it costs: - The fallback policy applies to **every** request that carries no authorization metadata, not just downloads. Public files served by a `UseStaticFiles` placed *before* `UseAuthorization` are unaffected, but anything after it is now members-only. - `MapStaticAssets` registers endpoints, so the fallback policy applies to them too; the documentation adds `AllowAnonymousAttribute` metadata through `MapStaticAssets().Add(...)` to keep the site's CSS and scripts public. - If you never call `UseAuthentication`/`UseAuthorization`, `WebApplication` inserts them for you **at the start of the pipeline (after its implicit `UseRouting` when endpoints exist), ahead of every middleware you wrote**. With a fallback policy in place, even the public `UseStaticFiles` then sits behind it, and the home page's stylesheet starts demanding a sign-in. ## Option 2: an authorized endpoint per download ```csharp app.MapGet("/downloads/{fileName}", Results<PhysicalFileHttpResult, NotFound> (string fileName, IWebHostEnvironment env) => { var provider = new PhysicalFileProvider( Path.Combine(env.ContentRootPath, "member-downloads")); var file = provider.GetFileInfo(Path.GetFileName(fileName)); return file.Exists && file.PhysicalPath is not null ? TypedResults.PhysicalFile(file.PhysicalPath, "application/octet-stream", file.Name, enableRangeProcessing: true) : TypedResults.NotFound(); }) .RequireAuthorization("Members"); ``` Here `Members` is a named policy registered with `AddAuthorization`. This design needs no global fallback policy, and it allows rules a folder cannot express: - a named policy (a paid membership tier, a role) instead of "any signed-in user"; - an audit log line or a download counter per file; - a `Content-Disposition` file name and range processing for large route books; - per-file decisions, such as hiding last season's files. The route value is user input. `Path.GetFileName` strips directory parts, and `PhysicalFileProvider` returns a not-found file for rooted paths or paths that climb above its root, and by default hides dot-prefixed, hidden and system files. ## Choosing between them | Concern | Fallback policy + `UseStaticFiles` | Endpoint + `RequireAuthorization` | |---|---|---| | Setup | one middleware call | one endpoint | | Rule | the fallback policy, for everything without metadata | any named policy, per endpoint | | Side effects | changes the default for the whole app | none outside the endpoint | | ETag, ranges, 304 | from the middleware | `TypedResults.PhysicalFile` with range processing | | Logging and per-file checks | not without extra middleware | in the handler | ## Details that bite in production - Send a caching header that keeps shared caches from storing members' files; `OnPrepareResponse` or the handler can set it. - A challenge from a cookie scheme redirects browsers to the login page, while API callers get 401. - Keep the members' folder out of the published `wwwroot`, so a later `MapStaticAssets` build never fingerprints it into a public URL. - Test it anonymously: request a known members' file without a cookie and confirm a challenge, not a 200, both locally and behind the production proxy. ## What interviewers listen for - Static files skip authorization; location and placement decide exposure. - The fallback policy as the mechanism that protects middleware-served files, and its app-wide side effects. - The endpoint alternative for anything finer than "signed in", with path validation.

  • Why call UseAuthentication and UseAuthorization explicitly here instead of letting WebApplication add them?
    When they are not called and their services are registered, `WebApplication` inserts them at the start of the pipeline, after its implicit `UseRouting`, before every middleware in Program.cs. With a fallback policy, the public `UseStaticFiles` then runs behind authorization and the site's stylesheet demands a sign-in. Calling them explicitly lets you put public files before them and the members' folder after.
  • In the endpoint version, how do you stop a request like /downloads/..%2F..%2Fappsettings.json from escaping the folder?
    Treat the route value as untrusted. `Path.GetFileName` drops any directory part, and resolving it through a `PhysicalFileProvider` rooted at the members' folder returns a not-found file for rooted paths or paths that navigate above the root. Return `TypedResults.NotFound()` when `Exists` is false instead of building a path with `Path.Combine` alone.

  • Putting [Authorize] on the controllers also protects the files under wwwroot.
  • Moving UseStaticFiles after UseAuthorization protects files even without a fallback policy.
  • A long random file name in wwwroot is adequate protection for members' files.
  • Combining the route value with the folder via Path.Combine needs no further validation.
  • A fallback policy only affects the static files registered after UseAuthorization.