How Content Security Policy should work with SPA?

427 Views Asked by At

We have two UI on SPA, one its app itself and another login UI. App calls several our backend services mostly API. Penetration testing showed that we must add CSP header.

Strange that in testing report they point calls from our login UI likes:

/assets/ourConfig.js

/assets/scripts/ourScript.js

And call

/.well-known/openid-configuration

And several PUT methods on api service that return simple OkResult()

Which services and when should send CSP headers? All service API?

2

There are 2 best solutions below

0
Halvor Sakshaug On

CSP is needed on pages with content, typically with content type "text/html". The resources that become content on a page don't need a CSP, neither does redirects. But it is adviced to use a CSP with "frame-ancestors 'none';" on APIs to prevent certain drag'n'drop style attacks.

0
Gary Archer On

The Content Security Policy is provided by a web server, that serves the static content. A CSP is not returned from APIs.

The above link provides examples. For something to compare against, see my example web host, which uses this CSP. Start with strict settings, then relax them as required, eg to include other trusted domains. This also works if you are deploying an SPA to a content delivery network:

const trustedHosts = this._configuration.trustedHosts.join(' ');
let policy = "default-src 'none';";
policy += " script-src 'self';";
policy += ` connect-src 'self' ${trustedHosts};`;
policy += " child-src 'self';";
policy += " img-src 'self';";
policy += " style-src 'self';";
policy += " object-src 'none';";
policy += " frame-ancestors 'none';";
policy += " base-uri 'self';";
policy += " form-action 'self'";

response.setHeader('content-security-policy', policy);

One of the benefits is reduced cross site scripting threats. An easy way to test this is to use an online site like Mozilla Observatory:

enter image description here