Jim Aho
Jim Aho

Reputation: 11957

Shall I use the Content-Security-Policy HTTP header for a backend API?

We're implementing HSTS on our backend API and I stumbled upon the Content Security Policy (CSP) header. This header tells the browser where from resources such as images, video, stylesheet, scripts and so on can be downloaded.

Since a backend API won't really display things in a browser, what's the value of having this header set?

Upvotes: 44

Views: 34219

Answers (2)

septiadi
septiadi

Reputation: 81

You may need it. Please refer to https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html#security-headers

For an API response, there is no requirement to be framed in any of those elements. Providing frame-ancestors 'none' prevents any domain from framing the response returned by the API call. This header protects against drag-and-drop style clickjacking attacks.

Upvotes: 2

DaSourcerer
DaSourcerer

Reputation: 6606

CSP is a technique designed to impair -attacks. That is, it is most useful in combination with serving hypermedia that relies on other resources being loaded with it. That is not exactly a scenario I would expect with an API. That is not to say you cannot use it. If there really is no interactive content in your responses, nothing could hold you from serving this header:

Content-Security-Policy: default-src 'none';

Going one step further, you could use CSP as some sort of makeshift Intrusion Detection System by setting report-uri in order to fetch incoming violation reports. That is well within the intended use but still a bit on the cheap.

In conclusion, it can theoretically improve the security of your API through little effort. Practically, the advantages may be slim to none. If you feel like it, there should be no harm in sending that header. You may gain more by e.g. suppressing MIME-type sniffing, though.

See also: The OWASP Secure Headers Project

Upvotes: 58

Related Questions