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

## Validate Content-Type In REST Services

Accepting any content type on your API endpoints can lead to unexpected parsing behavior or bypass security filters. For example, an attacker might send XML to an endpoint expecting JSON to trigger an XXE (XML External Entity) attack.

**Incorrect (no content-type validation):**

```kotlin
// Ktor: Receiving raw body without validation
post("/api/data") {
    val body = call.receiveText()
    // No check if this is JSON, XML, or plain text
    process(body)
}

// Spring Boot: Permissive mapping
@PostMapping("/api/data", consumes = ["*/*"])
fun handle(@RequestBody data: String) { ... }
```

**Correct (strict content-type validation):**

```kotlin
// Spring Boot: Explicit 'consumes' constraint
@PostMapping("/api/data", consumes = [MediaType.APPLICATION_JSON_VALUE])
fun handle(@RequestBody data: MyDataModel): ResponseEntity<Any> {
    return ResponseEntity.ok(Success())
}

// Ktor: Content-Type check in interceptor or route
post("/api/data") {
    val contentType = call.request.contentType()
    if (contentType.withoutParameters() != ContentType.Application.Json) {
        call.respond(HttpStatusCode.UnsupportedMediaType, "Only application/json is supported")
        return@post
    }
    val data = call.receive<MyDataModel>()
    // ...
}

// Multpart requirement for uploads
@PostMapping("/api/upload", consumes = [MediaType.MULTIPART_FORM_DATA_VALUE])
fun upload(@RequestParam("file") file: MultipartFile) { ... }
```

**Best Practices:**
- Use the `consumes` attribute in Spring's `@RequestMapping` or `@PostMapping`.
- Always return the `415 Unsupported Media Type` status code when the content type is not allowed.
- Ensure that the parser (JSON, XML) is configured securely (e.g., disabling external entities for XML).
- Avoid generic types like `application/octet-stream` unless specifically handling binary data.

**Tools:** Spring Security, Ktor ContentNegotiation, OWASP ZAP, API Gateway (e.g., Kong, AWS Gateway)
