We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Securing File Downloads

A protected file presents an easy-to-overlook authorization problem. Many file servers map URL paths to files, and if the server doesn't check that the requester is allowed to access a file, any authenticated user can download another user's file by changing the URL.

The simplest solution is often to avoid exposing the file directly. Instead, the server checks permission and then streams the file to the authorized user.

const file = findUploadedFileById(fileId);
if (
  !file ||
  (file.user_id !== current.user.id && !hasRole(current, "support", "admin"))
) {
  res.status(404).send("File not found");
  return;
}

res.download(file.storage_path, file.original_name);

Express's res.download (from the example) simply sets download-oriented response headers and streams a file from a path on disk. It doesn't decide who should receive that file – so the authorization check needs to happen before it's called.

The storage path should also come from trusted server-side metadata, not directly from a URL parameter. Treat the URL's file ID as an untrusted reference, then resolve it through a database or other server-side mapping.

A secure direct-download flow follows one guarded path:

  1. Authenticate the requester.
  2. Load the file metadata.
  3. Authorize access to that file.
  4. Send the file to the authorized requester.

Assignment

Bearly Secure lets any authenticated user download any tax-exemption document by changing the file ID. Secure the download route while preserving legitimate customer, support, and administrator access.

With Bearly Secure still running, run and submit the CLI tests from the project root.