Secure File Serving and Access Control
What you'll learn: How to safely serve uploaded files while preventing unauthorized access and execution vulnerabilities.
The Core Problem
After users upload files, you need to serve them back safely. The danger? If attackers can directly access uploaded files without checks, they might execute malicious code, access other users' private documents, or bypass authentication entirely. Think of it like a library where books must be checked out through a librarian—not grabbed directly from storage shelves.
Why Application-Layer Serving Matters
Never serve uploaded files from a publicly accessible directory. Instead, route all file requests through your application code where you can enforce:
- Authentication checks – Is the user logged in?
- Authorization checks – Does this user have permission to access this specific file?
- Rate limiting – Prevent bulk downloading attacks
Store uploaded files outside your webroot (e.g., /var/app/uploads/ instead of /var/www/public/uploads/) so web servers can't serve them directly.
Content-Disposition Headers
Force browsers to download files safely rather than rendering them inline:
Content-Disposition: attachment; filename="document.pdf"
This prevents browsers from executing JavaScript in HTML files or running other active content. For trusted content you want displayed, use inline, but combine it with strong Content-Type validation.
The Secure Flow
- User requests
/download?file_id=123 - Application verifies user authentication
- Application checks user owns or has permission for file ID 123
- Application reads file from protected storage
- Application sets secure headers (Content-Disposition, Content-Type)
- Application streams file to user
Key Takeaway: Always serve uploaded files through application logic with authentication and authorization checks, use Content-Disposition headers to control browser behavior, and store files outside publicly accessible directories to prevent direct access vulnerabilities.