How to Secure File Downloads with Presigned URLs
Serve private files through short-lived signed URLs so storage credentials stay on the server and access is time-bounded.
On this page
Introduction
Serving private files means the browser must fetch them from storage without holding the storage credentials. Proxying every download through the application works but ties up application capacity and bandwidth for large files. A presigned URL is the alternative: the server uses its credentials to sign a URL that grants access to one object for a limited time, and the client downloads directly from storage. This article covers how signing works, how to bound the access, the risks the URL introduces, and how to combine it with authorization so a signed URL is not a bearer credential that outlives the user’s right to the file.
Why Not Proxy Every Download
Proxying a download through the application keeps the storage credentials on the server, which is good, but it makes the application serve bytes for every file, consuming its bandwidth, memory and connections for a task the storage service is built to do. For large files or high download volume, the application becomes the bottleneck and the cost scales with the data transferred rather than with the requests.
A presigned URL moves the transfer to the storage service while keeping the decision with the application. The application authorizes the request, signs a URL, and hands it to the client; the client fetches directly from storage. The application no longer carries the bytes, but it still controls who gets a URL.
How Presigning Works
The server constructs a request to the storage API, including the object key, the method and an expiration, then signs it with a credential that has access to the object. The signature and the parameters are appended to the URL. Storage validates the signature and the expiry when the client uses the URL, and rejects it if the signature is invalid or the time has passed.
import boto3
from botocore.config import Config
s3 = boto3.client('s3', config=Config(signature_version='s3v4'))
def presigned_download(bucket: str, key: str, expires_in: int = 300) -> str:
"""Return a short-lived URL that allows a GET on exactly one object."""
return s3.generate_presigned_url(
'get_object',
Params={
'Bucket': bucket,
'Key': key,
# Force a download filename and forbid inline rendering of active
# content, so a signed URL cannot be used to run HTML/JS in the app's
# origin.
'ResponseContentDisposition': 'attachment',
'ResponseContentType': 'application/octet-stream',
},
ExpiresIn=expires_in, # seconds; keep it short
)
Bounding the Access
The two knobs that bound a presigned URL are its scope and its lifetime. Scope: sign for one object and one method, not a prefix or a bucket, so the URL cannot be altered to read another file. Lifetime: keep it short, minutes rather than hours, so a leaked URL is useful only briefly. A URL that grants access to a prefix for a day is a broad credential, not a link to a file.
Some storage services support conditions in the signature, such as a maximum content length or an IP range, which further bound what the URL can do. Use them where available. The principle is to make the signed URL the narrowest grant that still lets the client complete the download.
Authorization and Leakage
A presigned URL is a bearer credential: anyone who holds it can use it until it expires. So the application must decide, before signing, whether this user may download this file, and the URL must be scoped to exactly that file. Checking authorization at signing time is the correct place; checking it later is impossible because the client goes straight to storage.
Bound the damage from leakage by keeping the lifetime short, by not embedding the URL in a page a third party can read, and by logging who requested a signed URL for which object. If a URL is sent through a channel that logs it, such as an email or a chat, assume it may leak and keep its lifetime correspondingly short. Never put a long-lived URL in a place that gets archived.
Storing and Serving Content Safely
Signing a URL for user-uploaded content is risky if that content can be executed: an HTML file rendered inline can run scripts in the storage domain or, worse, an origin shared with the application. Force a download disposition and a non-executable content type, or serve uploads from a separate origin that has no privileges. This is how a file-download feature becomes a stored-XSS vector.
Validate uploads by content, not by extension, and store them outside any path the application serves directly. Treat the object key as untrusted: construct it from a server-generated identifier, not from the client’s filename, so a crafted name cannot escape a prefix or collide with another user’s object. The same discipline as path containment applies to object keys.
import os, uuid
ALLOWED_MAGIC = {
b"\x89PNG\r\n\x1a\n": "image/png",
b"\xff\xd8\xff": "image/jpeg",
b"%PDF-": "application/pdf",
}
def safe_object_key(tenant_id: str, data: bytes) -> str:
"""Build the storage key server-side from a generated id, never the client
filename, and reject uploads whose bytes do not match an allowed type."""
kind = next((m for m in ALLOWED_MAGIC if data.startswith(m)), None)
if kind is None:
raise ValueError("unsupported or mismatched file content")
# Key is derived from tenant + a random id; the client filename is ignored
# for the path, so it cannot traverse or collide.
return f"tenants/{tenant_id}/uploads/{uuid.uuid4()}"
Operational Concerns
Because the transfer bypasses the application, you lose the per-request visibility you would have had proxying. Log the signing events (who, which object, when, with what lifetime) so you can audit access and investigate an incident. Emit a metric for signed URLs issued, and alert on anomalies such as one user signing URLs for many objects quickly.
Handle expiry gracefully: a client that receives a URL, waits, and then tries to download gets a 403 because the URL expired. Either issue the URL immediately before use or make the client request a fresh URL on failure. A download that fails silently because of an expired URL is a support ticket you can avoid.
Conclusion
Presigned URLs let a client download private files directly from storage, keeping the storage credentials on the server and the transfer out of the application. Sign for a single object and method, keep the lifetime short, and decide authorization before signing because the URL is a bearer credential. Force a download disposition and a non-executable content type so user content cannot execute, construct object keys server-side, and log every signing event. Then the URL is a narrow, time-bounded grant rather than a leaked credential.
Sources: AWS S3: presigned URLs, OWASP: File Upload Cheat Sheet, Content-Disposition header.
FAQ
- Is a presigned URL safe to share?
- It is a bearer credential: anyone who holds it can use it until it expires. Keep it scoped to one object and one method, keep the lifetime short, and decide authorization before signing. Treat it as a link that may leak and bound the damage accordingly.
- Why force a download disposition on user-uploaded files?
- Because content rendered inline can execute: an HTML or SVG file served inline can run scripts in the storage origin. Forcing an attachment disposition and a non-executable content type avoids turning a file download into stored XSS.
Report a problem with this articleOpens a pre-filled issue on GitHub.