How Content Security Policy Shields Your Site from XSS Attacks
Content Security Policy (CSP) is a browser‑level defense that defines a whitelist of trusted sources for scripts, styles, images, and other resources, preventing malicious code injection such as XSS by blocking any content not explicitly allowed.
CSP (Content Security Policy) is a security mechanism that helps prevent cross‑site scripting (XSS) by allowing a website to declare a whitelist of trusted origins for external resources.
The core idea is to define which sources are permitted. For example, if a page normally loads a script from http://a.com/x.js, an attacker might try to inject a script from http://b.com/x.js. With CSP, the browser will only execute scripts whose origin appears in the whitelist.
By adding a CSP header such as: Content-Security-Policy: script-src 'self' http://a.com the browser will reject any script from other domains, effectively blocking the malicious payload.
CSP provides a set of directives that control different types of resources:
default-src : fallback source list used when a specific directive is not defined.
script-src : allowed script origins; also disables inline scripts and eval() unless 'unsafe-inline' or 'unsafe-eval' are explicitly permitted.
style-src : allowed stylesheet origins.
img-src : allowed image origins.
font-src : allowed font origins.
frame-src : allowed origins for <frame> and <iframe> elements.
connect-src : allowed endpoints for XHR, WebSocket, EventSource, etc.
media-src : allowed audio and video sources.
object-src : allowed Flash and other plug‑in objects.
content-src : limits the types of connections (e.g., XHR, WebSocket).
An example policy might be:
default-src 'none';
script-src http://cdn.my.com;
style-src http://cdn.my.com;
img-src http://cdn.my.com;
connect-src http://api.my.com;
frame-src 'self';This configuration blocks all content by default, trusts only http://cdn.my.com for scripts, styles, and images, allows data connections only to http://api.my.com, and restricts frames to the same origin.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
