Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

You must add a Content-Security-Policy to a large server-rendered application with inline scripts and third-party widgets, without breaking it. How do you proceed?

Start with Content-Security-Policy-Report-Only and a report endpoint, so the browser tells us what a draft policy would block without breaking anything. Then remove inline scripts, or give the ones that must stay a per-request nonce or a hash, list the third-party origins the widgets need explicitly instead of using wildcards, and tighten the policy step by step. Switch to the enforcing header once reports are clean, and keep monitoring them because new features will try to break the policy.

Why this question is asked

Adding a CSP to a new application is easy. Adding one to a large server-rendered application, built over years with inline onclick handlers, script blocks in templates and a handful of third-party widgets, is a project, because a strict policy enforced on day one would break pages for real users. Interviewers ask this scenario to see whether we can introduce a strong control safely, using data rather than guesses. In this answer, we will recap what CSP does, collect violations in report-only mode, deal with inline scripts using nonces and hashes, handle third-party widgets, tighten the policy in stages, and keep it healthy once enforced.

1A Quick Recap of CSP

Content-Security-Policy is a response header that lists where a page may load resources from: script-src for scripts, style-src for styles, img-src for images, connect-src for fetch and XHR, frame-src for frames, and so on. If an attacker injects <script>alert(1)</script> into a page, a policy with script-src 'self' makes the browser refuse to run it, because inline scripts are not allowed unless the policy permits them.

That last point is why legacy applications are hard. A strict policy blocks all inline script, including the application's own onclick handlers and script blocks, and all third-party scripts not listed. So we need to find all of them first.

2Report Only, Then Read the Reports

The browser supports a second header, Content-Security-Policy-Report-Only. It applies the policy in observation mode: nothing is blocked, but every violation is reported to an endpoint we choose. That lets us test a draft policy on real traffic and real browsers, with zero risk to users.

Java
http.headers(h -> h.contentSecurityPolicy(csp -> csp
.policyDirectives("default-src 'self'; script-src 'self'; " +
"object-src 'none'; base-uri 'self'; report-uri /csp-reports")
.reportOnly())); // sends Content-Security-Policy-Report-Only
@PostMapping(path = "/csp-reports", consumes = {"application/csp-report", "application/json"})
ResponseEntity<Void> report(@RequestBody String body) {
cspReports.record(body); // aggregate by blocked-uri, directive and page
return ResponseEntity.noContent().build();
}
// a page with <button onclick="save()"> produces a report: script-src-attr, inline

The reports name the page, the directive that would have been violated and the blocked source. We aggregate them, for example by directive and blocked source, rather than reading them one by one, because a busy site produces thousands. The newer reporting mechanism uses report-to with a Reporting-Endpoints header; report-uri is older but still widely supported, so many teams send both. Browser extensions also cause reports, so some noise is expected. Once nonces are introduced in the next step, the header is written by a small filter instead, because its value changes per response.

3Remove Inline Scripts or Mark Them with Nonces

The reports will mostly be inline script. The cleanest fix is to move it out: inline onclick="save()" handlers become addEventListener calls in a static JavaScript file, and script blocks become files. Static files are allowed by script-src 'self'.

Some inline scripts must stay, for example a small block that passes server data to the page. For those we use a nonce: a random value generated for every response, put into the CSP header and into the script tag. The browser runs only inline scripts whose nonce matches the header. An attacker who injects a script cannot guess this response's nonce.

Java
// filter: one nonce per request, exposed to templates
String nonce = Base64.getEncoder().encodeToString(randomBytes(16));
request.setAttribute("cspNonce", nonce);
response.setHeader("Content-Security-Policy-Report-Only",
"script-src 'self' 'nonce-" + nonce + "'; object-src 'none'; base-uri 'self'; report-uri /csp-reports");
<!-- Thymeleaf template -->
<script th:attr="nonce=${cspNonce}">window.config = { userId: [[${userId}]] };</script>
<!-- runs: nonce matches. An injected <script> without the nonce: blocked (or reported) -->

Notice that the nonce must be new for every response and unpredictable; a fixed nonce gives no protection. Spring Security does not generate CSP nonces itself, so this filter is our own code, written once and shared. For an inline script whose content never changes, a hash ('sha256-...') of its content works too and needs no per-request value. Inline event handlers like onclick cannot use nonces, so those must be rewritten.

4List Third-Party Origins Explicitly

Widgets such as a chat tool, analytics, a payment form or a map load scripts, frames and connections from their own domains. The reports show exactly which ones. We add each origin to the specific directive it needs, such as script-src https://widget.chatvendor.com and frame-src https://js.payments.example, rather than allowing https: or *. A broad wildcard would let an attacker load script from any domain they control, which defeats the policy.

Some widgets load further scripts from changing hosts or require 'unsafe-inline' or 'unsafe-eval'. That is worth raising with the vendor, checking their CSP documentation, or isolating the widget in a sandboxed iframe on a separate origin, because every exception weakens the policy for the whole page.

5Tighten in Stages and Switch to Enforcing

We do not aim for the final policy in one step. A practical order is to enforce the easy, safe directives first, such as object-src 'none', base-uri 'self' and frame-ancestors, while script-src stays in report-only. Then we fix inline scripts page by page, release by release, until reports for script-src are down to noise. Then we switch script-src to enforcing too, keeping a report-only header in parallel for the next, stricter version.

Where the application can support it, the target is a nonce-based policy with 'strict-dynamic', which trusts scripts loaded by already-trusted scripts and is easier to maintain than long host lists. Check browser support for the features you rely on.

Step throughRolling out CSP without breaking pages
  1. Report-only with draft policyCollect and aggregate reports
  2. Fix inline scriptsMove to files; nonces or hashes for the rest
  3. List widget originsExact hosts per directive, no wildcards
  4. Enforce safe directivesobject-src, base-uri, frame-ancestors
  5. Reports clean for script-src?Only noise left
    YesEnforce full policyNoKeep fixing
  6. Keep monitoringAlert on new violations

6 steps in order. Play them, or step through them one at a time.

6Keep the Reports Monitored

After enforcement, reports become an early warning system. A new feature with an inline script, a vendor that changes its script host, or an actual injection attempt all show up as violations. We keep the report endpoint, put the aggregated counts on a dashboard and alert on a rise in violations from our own pages. A browser test in CI that loads key pages and fails on CSP violations in the console catches most regressions before release.

7Follow-up questions

Why not just allow 'unsafe-inline' to get started?

Because it allows exactly what XSS needs: any injected inline script runs. A policy with 'unsafe-inline' in script-src gives little protection against XSS. It is better to run report-only for longer than to enforce a policy that permits inline script.

Does CSP replace output encoding?

No. Encoding prevents injection; CSP limits what an injection can do if one slips through. A strong application uses both.

How long should the report-only phase last?

Long enough to cover the application's real traffic, including rare pages and monthly jobs, typically a few weeks per stage. The reports, not the calendar, decide when to enforce.

8Conclusion

In this answer, we rolled out a CSP on a large legacy application in stages. Report-only mode with a report endpoint showed what a draft policy would block. Inline scripts were moved into files or given per-request nonces or hashes, third-party origins were listed explicitly, and the policy was tightened directive by directive before switching to enforcement. Monitoring the reports afterwards keeps new features from breaking the policy or weakening it.

What to say in the interviewAbout 90 seconds aloud

Open with

I would never enforce a strict policy on day one, because it would break inline scripts and widgets for real users. I would start with Content-Security-Policy-Report-Only and a report endpoint, so browsers report what a draft policy would block without blocking anything.

Then, if they want more

I would aggregate the reports by directive and blocked source to see the real picture.

Most violations in an older server-rendered app are inline scripts, so the next step is to move inline handlers and script blocks into static files, and for the inline scripts that must stay, use a nonce: a random value per response, set in the header and on the script tag through Thymeleaf, or a hash for scripts that never change.

Spring Security does not generate nonces, so that is a small shared filter. For third-party widgets, I would take the exact origins from the reports and add them to the specific directives they need, never https or star, and push vendors that need unsafe-inline or isolate them in a sandboxed iframe.

Then I tighten in stages: enforce the easy directives like object-src none, base-uri and frame-ancestors first, keep script-src in report-only until the reports show only noise, and then switch it to enforcing.

After that I keep the reports on a dashboard with alerts, and add a browser test that fails on CSP violations, because new features will keep trying to add inline script.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
OWASP Top Ten
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "You must add a Content-Security-Policy to a large server-rendered application with...": https://scrivio-interview-library.netlify.app/spring-boot/web-security-threats/d0ce6334dc/