Introduction
The Content Security Policy (CSP) is a browser security mechanism that helps reduce the risks of Cross-Site Scripting (XSS) and content injection. The Sonata-Extra bundle for Symfony provides an effective way to implement and manage CSP in your application.
Understanding the Content Security Policy
CSP is transmitted through a response header and allows you to control the resources your web page can load or execute. By specifying a list of trusted sources, you can reduce the risk of malicious content injections.
Key concepts
- Directives: These are the rules that define which resources can be loaded. Each directive controls a specific type of resource, such as scripts, styles, images, etc.
- Sources: Under each directive, you specify sources (such as URLs) from which the resource can be loaded.
Security types in the Sonata-Extra bundle
In Sonata Extra Bundle, SECURITY_TYPES is a constant table that associates CSP directives with their configuration keys. Here is a breakdown of each directive:
default-src
Default fallback for most directives. Controls the default sources for different types of content.
script-src
Defines the valid sources for JavaScript. Options include:
'self': Only load scripts from the same origin.'unsafe-inline'Allow online scripts, although it is less safe.- Specific URLs: Define the allowed external scripts.
style-src
Specifies the valid sources for style sheets. Options similar to script-src.
img-src
Controls the sources from which images can be loaded.
connect-src
Limits the origins to which you can connect (for example, WebSockets, AJAX requests).
font-src
Defines the sources of font files.
object-src
Check the sources for elements such as <object>, <embed>, etc.
media-src
Specifies the sources for loading media (audio and video).
frame-src
Determine the valid sources for frames and iframes.
Other directives
child-src,form-action,frame-ancestors,manifest-src,base-uri,sandbox,report-uri,worker-src,navigate-to: These further refine policies for specific use cases.
Implementation of the CSP in the Sonata-Extra bundle
Configuration
Define your CSP policies in a YAML configuration file under partitech_sonata_extra. For example:
partitech_sonata_extra:
content_security_policy:
object-src:
- 'none'
script-src:
- 'self'
- 'unsafe-inline'
- 'https://external.script.url'
style-src:
- 'self'
- 'unsafe-inline'
- 'https://external.stylesheet.url'
font-src:
- 'self'
- 'https://cdnjs.cloudflare.com/'
- 'https://fonts.gstatic.com/'
Validate the policy before its deployment


Start by monitoring violations in report mode, then tighten the allowed sources. A CSP does not replace output escaping or input validation.