'Do frontend and backend sub domain needs to be same to have the effect of CSP headers from https response?

Let's say I have a website "webapp.abc.com" and my backend is hosted on "api.abc.com"

Now whenever my Frontend (webapp.abc.com) calls an API of (api.abc.com) then I get some CSP headers in the response

Now my question is I am getting these CSP headers from a different sub domain (api.abc.com) than my Frontend (webapp.abc.com), so what will happen...will the browser apply this CSP header that i got from the response of "api.abc.com" or is it necessary to have our Frontend and Backend sub domain be the same to have the effects of these headers on my website



Solution 1:[1]

CSP is a policy for content, which typically has content type "text/html" and is rendered in your browser. An API typically serves data and a CSP doesn't really make any difference. There are however situations in which it can be useful, see https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html#security-headers

In this case you will instead need to configure your Cross Origin Resource Sharing (CORS) headers. You will need to set at least Access-Control-Allow-Origin. You should not set it to * or just reflect the origin of the request if the data isn't public. You might also need to set other CORS headers such as Access-Control-Allow-Credentials if authentication is required. Please try to understand CORS headers before implementing as they are relaxing the security defaults browsers are applying for your data's safety.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Halvor Sakshaug