CSP: connect-src

HTTP 协议头部Content-Security-Policy (CSP) 的**connect-src** 指令用于控制允许通过脚本接口加载的链接地址。其中受到影响的 API 如下:

CSP version 1
Directive type Fetch directive
default-src fallback Yes. If this directive is absent, the user agent will look for the default-src directive.

Syntax

connect-src 可以设置一个或者多个源地址:

Content-Security-Policy: connect-src <source>;
Content-Security-Policy: connect-src <source> <source>;

Sources

<source> can be any one of the values listed in CSP Source Values.

Note that this same set of values can be used in all fetch directives (and a number of other directives).

Examples

Violation cases

给定如下 CSP 头部:

Content-Security-Policy: connect-src https://example.com/

如下的连接请求会被阻塞且不会加载:

<a ping="https://not-example.com">

<script>
  var xhr = new XMLHttpRequest();
  xhr.open('GET', 'https://not-example.com/');
  xhr.send();

  var ws = new WebSocket("https://not-example.com/");

  var es = new EventSource("https://not-example.com/");

  navigator.sendBeacon("https://not-example.com/", { ... });
</script>

Specifications

Specification
Content Security Policy Level 3
# directive-connect-src

Browser compatibility

BCD tables only load in the browser

Compatibility notes

  • Prior to Firefox 23, xhr-src was used in place of the connect-src directive and only restricted the use of XMLHttpRequest.

See also