connect-srcContent Security Policy (CSP) directive guards the several browsers mechanisms that can fetch HTTP Requests. This includes
XMLHttpRequest(XHR / AJAX),
Web Browsers have several mechanisms to invoke HTTP requests from script, and CSP has the sovereignty to control the endpoints that can be requested.
connect-src CSP directive does not interfeer Cross-Origin Resource Sharing (CORS) headers, so the same origin policy still applies.
In most cases you will be making XMLHttpRequests to the same origin (the same domain and scheme), for example:
var xhr = new XMLHttpRequest(); xhr.open('GET', '/api.json'); xhr.send();
In that case you will only need to set the
connect-src directive to
Content-Security-Policy: connect-src 'self';
If you are attempting to request a domain using XMLHttpRequest that is not the same origin, then you will need to specify that domain in the
connect-src directive. Due to the browsers Same Origin policy, you will also need to ensure that the proper CORS headers have been set to allow your domain to connect to the third party domain.
For example supplse we are making an XMLHttpRequest to api.example.com from app.example.com:
var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://api.example.com/api.json'); xhr.send();
First you will need to have api.example.com in your connect-src directive.
Content-Security-Policy: connect-src 'self' https://api.example.com;
If we forgot to do this our request would fail with something like this in the developer tools console:
Refused to connect to
'https://api.example.com'because it violates the following content security policy directive:
api.example.com server needs to permit
app.example.com via a CORS
Access-Control-Allow-Origin header. For example:
When a resources is blocked due to
connect-src the browser emulates a 400 HTTP status code.
Besides XMLHttpRequest or ajax calls, the connect-src directive also applies to the following browser mechanisms:
connect-src CSP directive applies to the fetch() api.
var promise = fetch('https://api.example.com/api.json');
When using the Beacon API, the CSP
connect-src directive applies.
The EventSource API will also fall under the control of the
connect-src CSP directive.
var es = new EventSource('https://example.com/');
The use of WebSockets is controlled by the
var ws = new WebSocket('wss://ws.example.com/');
When using the
ping attribute of the
a tag, you must specify the endpoint in the
connect-src CSP directive.
<a href="https://example.com/" ping="https://log.example.com/ping">Go</a>
If you do not specify a
connect-src directive, but do specify a
default-src directive then the value of the
default-src directive is used.
connect-src directive has been part of the Content Security Policy Specification since the first version of it (CSP Level 1).
Internet Explorer 11 and below do not support the CSP
connect-src directive. This means that IE11 will simply ignore the policy and allow AJAX requests as long as allowed by CORS.