ASP.NET Core MVC Interview Question #189

How would you implement secure file downloads?

Senior Practical MVC Scenarios & Production Architecture Senior Advanced

Quick Interview Answer

Authorize access to the logical file record before reading the physical object. Resolve the storage location from trusted server-side metadata rather than accepting an arbitrary path from the request.

Detailed Explanation

Authorize access to the logical file record before reading the physical object. Resolve the storage location from trusted server-side metadata rather than accepting an arbitrary path from the request.

Return an appropriate content type and download filename. Protect against path traversal and avoid exposing internal storage paths to the client.

Code Example

var document = await _documents.GetAsync(id, token);
if (document == null)
    return NotFound();

if (!await _permissions.CanDownloadAsync(User, document))
    return Forbid();

return PhysicalFile(
    document.SafePath,
    document.ContentType,
    document.DownloadName);