Content-Type Validation
Verifying and enforcing correct Content-Type headers on both requests and responses to prevent MIME-based attacks.
Description
Content-Type validation is the practice of verifying that the Content-Type header in HTTP requests matches the actual content being sent, and that responses include correct, explicit Content-Type headers to prevent browsers from guessing content types. MIME type confusion attacks exploit the mismatch between declared and actual content types to execute malicious code, bypass security controls, or trigger unintended behavior in the application.
On the request side, applications should validate that incoming Content-Type headers match the expected format for each endpoint. An API endpoint expecting JSON should reject requests with Content-Type: application/x-www-form-urlencoded or multipart/form-data unless explicitly designed to accept them. Without this validation, attackers can craft requests that bypass CSRF protections (since some Content-Types trigger preflight CORS checks while others don't) or exploit parser differentials between what the Content-Type declares and what the server actually parses.
On the response side, setting the X-Content-Type-Options: nosniff header is essential to prevent browsers from performing MIME sniffing -- where the browser ignores the declared Content-Type and guesses the type from the content. Without nosniff, a file served as text/plain might be interpreted as HTML if it contains HTML-like content, leading to XSS. Additionally, responses should always include an explicit Content-Type header with the correct MIME type and charset (e.g., application/json; charset=utf-8) rather than relying on defaults or omitting the header entirely.
Prompt Snippet
Validate request Content-Type on all API endpoints: reject requests where the Content-Type doesn't match the expected format (return 415 Unsupported Media Type). In Express, use middleware to enforce application/json for JSON APIs and reject unexpected types. Set X-Content-Type-Options: nosniff on all responses to prevent MIME sniffing. Always include explicit Content-Type headers with charset in responses: res.type('application/json; charset=utf-8'). For file download endpoints, set Content-Type based on validated file metadata (not user input), pair with Content-Disposition: attachment, and never rely on file extensions alone. Use the mime-types package to map validated extensions to MIME types rather than hardcoding.Tags
Related Terms
Security Headers
HTTP response headers that instruct browsers to enable security mechanisms, reducing the attack surface of web applications.
File Upload Security
Security measures to prevent malicious file uploads from compromising the server, other users, or the application.
Input Validation & Sanitization
The practice of verifying and cleaning all user-supplied data before processing to prevent injection attacks and data corruption.