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.

DirectiveControlsExample
default-srcfallback for all types'self'
script-srcJavaScript'self' https://checkout.razorpay.com
img-srcimages'self' https://cdn.shopease.in data:
connect-srcfetch / XHR / WebSocket'self' https://api.shopease.in
frame-ancestorswho may embed this page'none' (modern X-Frame-Options)
object-src, base-uriplugins, <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' in script-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'.