Careeroza
Content Security Policy
What CSP Does
Content Security Policy tells the browser which sources of scripts, styles, images and connections are allowed. Even if an attacker injects <script> into a product review (XSS), the browser refuses to run it because inline scripts and unknown domains are not in the policy.
| Directive | Controls | Example |
|---|---|---|
default-src | fallback for all types | 'self' |
script-src | JavaScript | 'self' https://checkout.razorpay.com |
img-src | images | 'self' https://cdn.shopease.in data: |
connect-src | fetch / XHR / WebSocket | 'self' https://api.shopease.in |
frame-ancestors | who may embed this page | 'none' (modern X-Frame-Options) |
object-src, base-uri | plugins, <base> tag | 'none', 'self' |
Configure It
http.headers(headers -> headers
.contentSecurityPolicy(csp -> csp.policyDirectives(
"default-src 'self'; " +
"script-src 'self' https://checkout.razorpay.com; " +
"style-src 'self' https://fonts.googleapis.com; " +
"font-src 'self' https://fonts.gstatic.com; " +
"img-src 'self' https://cdn.shopease.in data:; " +
"connect-src 'self' https://api.razorpay.com; " +
"frame-src https://api.razorpay.com; " +
"frame-ancestors 'none'; object-src 'none'; base-uri 'self'; form-action 'self'")));Tip: Roll out CSP safely: first add .reportOnly() after policyDirectives(...). Browsers then only report violations (header Content-Security-Policy-Report-Only) and break nothing. Fix the reports for a week, then enforce.
CSP and React
- A Vite or Create React App production build has no inline scripts, so
script-src 'self'works. - Avoid
'unsafe-inline'and'unsafe-eval'inscript-src; they switch off most of CSP's protection. - If the React app is served by Nginx or a CDN, set the CSP header there; the Spring API mainly needs
frame-ancestors 'none'.