ASP.NET Core Web API Interview Question #184

How should secure file downloads be implemented?

Senior API Design, Architecture, Scalability & Production Scenarios Senior Advanced

Quick Interview Answer

Authorize access to the requested file before returning its contents. Resolve the storage object using a server-controlled identifier rather than accepting arbitrary filesystem paths from the client.

Detailed Explanation

Authorize access to the requested file before returning its contents. Resolve the storage object using a server-controlled identifier rather than accepting arbitrary filesystem paths from the client.

Set an appropriate content type and download filename, prevent path traversal, and consider short-lived signed storage URLs when clients can safely download directly from object storage.

Code Example

[Authorize]
[HttpGet("files/{id:guid}")]
public async Task<IActionResult> Download(
    Guid id,
    CancellationToken token)
{
    var file = await _files.GetAuthorizedAsync(User, id, token);
    if (file == null) return NotFound();

    return File(file.Stream, file.ContentType, file.DownloadName);
}