Skip to content

JSONP 与不安全的回调

JSONP 通过 <script src="https://api.example/data?callback=foo"> 跨域读数据,本质是 执行任意回调,已被 CORS 大规模取代。遗留接口若 回调名可控,可导致 XSS(回调注入)或 敏感数据泄露给任意域名


JSONP 回调注入示意

text
GET /profile?callback=alert(1)//

若服务端返回:

js
alert(1)// ({ "user": "admin" })

浏览器执行即弹出(示意)。


正确方向:弃用 JSONP

js
fetch('https://api.example/profile', {
  credentials: 'include',
})
  .then((r) => r.json())

服务端配置 精确 CORS + Cookie SameSite / Token,替代 JSONP。


若短期无法下线 JSONP

  1. 回调名白名单:仅允许 cb1cb2 等固定枚举。
  2. 响应 Content-Type: application/json 对纯 JSON,勿混脚本。
  3. 敏感接口禁止 JSONP,仅公开只读数据可走临时方案。

小结

新项目 不要使用 JSONP;老项目收紧 回调参数 并逐步迁移 HTTPS + CORS + 鉴权