---
title: Validate Content-Type In REST Services
impact: MEDIUM
impactDescription: prevents content-type confusion attacks and ensures predictable parsing
tags: rest, content-type, validation, api, security, php
---

## Validate Content-Type In REST Services

Accepting unexpected content types (e.g., XML when you expect JSON) can lead to parsing vulnerabilities like External Entity (XXE) attacks or bypass security filters that only check for specific formats. Strict `Content-Type` validation ensures your application only processes data in the formats it was designed to handle.

**Incorrect (accepting any content type):**

```php
// No content-type check: logic might try to parse different formats
public function store(Request $request) {
    // If the client sends XML but the code expects JSON, this might crash or behave unexpectedly
    $data = $request->all();
    $this->service->process($data);
}
```

**Correct (enforcing Content-Type via Middleware):**

```php
// 1. Plain PHP Validation
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
if (strpos(strtolower($contentType), 'application/json') === false) {
    header('HTTP/1.1 415 Unsupported Media Type');
    die("Only application/json is supported.");
}

// 2. Laravel Middleware (Recommended)
public function handle($request, Closure $next, ...$allowedTypes)
{
    $contentType = $request->header('Content-Type');

    if (!$contentType || !Str::contains(strtolower($contentType), $allowedTypes)) {
        return response()->json([
            'error' => 'Unsupported Media Type',
            'allowed' => $allowedTypes
        ], 415);
    }

    return $next($request);
}

// Route Usage:
Route::post('/api/data', [DataController::class, 'store'])
    ->middleware('validate.content:application/json');
```

**Why it matters?**
- **XXE Prevention**: If you only expect JSON but a user sends XML with a malicious DOCTYPE, your server might be vulnerable to Local File Read or SSRF if an XML parser is automatically triggered.
- **Strict Parsing**: Ensures that your data validation rules are applied to the correct format.
- **API Standards**: Returning a `415 Unsupported Media Type` is the correct RESTful way to communicate protocol mismatches.

**Tools:** Laravel Middleware, Symfony Request Matcher, OWASP ZAP, Postman (testing)
