Search code examples
securitycontent-security-policy

Why would a REST API need a CSP?


I’m trying to better understand Content Security Policies. My understanding is that they are an instruction to the browser of where certain parts of the page are allowed to be loaded from - images, media, scripts etc.

But I can’t figure out why a server whose purpose is to respond to requests for data - JSON for example - would need a CSP. It only provides data for other parties to consume. There is no browser involved.

So why would a REST API need a CSP? Is my understanding in the first paragraph incorrect?


Solution

  • As @Nick mentioned in the comment-section, a CSP may specified allowed domains and that TLS is needed. But, besides of that, even though your API does not require to be requested from browsers, it may be reached to from browsers.

    If you do not specify CSP, then you do not allow your site to be reached from browsers that refuse to serve unspecified servers.

    Assuming that your API is on domain1 and I own domain2 where I want to request end points from your server, you exclude my domain2 from doing so on the client-side and you force such third-parties to send their requests from the server-side, which may be unfeasible for them. If that's intentional, then all good. But if you want my domain to be allowed to request your domain's API from any app, browser or not, then you need to specify that.

    If you want to allow requests from any source, then you also need to specify CSP accordingly.

    So it's not about whether your API can be requested from other sources than browsers, but whether you want to allow your site to be reached from client-side requests from browsers, whether you want to enforce TLS, stuff like that.