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

## Validate Content-Type In REST Services

Accepting unexpected content types can lead to parsing vulnerabilities or bypass security controls.

**Incorrect (accepting any content):**

```go
func Handler(w http.ResponseWriter, r *http.Request) {
    // No check on Content-Type header
    var data map[string]interface{}
    json.NewDecoder(r.Body).Decode(&data)
}
```

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

```go
func validateContentType(allowed ...string) func(http.Handler) http.Handler {
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            ct := r.Header.Get("Content-Type")
            
            isValid := false
            for _, a := range allowed {
                if strings.Contains(strings.ToLower(ct), strings.ToLower(a)) {
                    isValid = true
                    break
                }
            }
            
            if !isValid {
                http.Error(w, "Unsupported Media Type", http.StatusUnsupportedMediaType)
                return
            }
            
            next.ServeHTTP(w, r)
        })
    }
}

// Router usage
mux.Handle("/api/data", validateContentType("application/json")(http.HandlerFunc(Handler)))
```

**Tools:** API Gateway, Middleware, OWASP ZAP
