### Configure Permissions Policy with Examples
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/configuration.md
Example configuration for Permissions Policy, demonstrating how to enable it and set directives for camera, microphone, geolocation, and fullscreen.
```yaml
nelmio_security:
permissions_policy:
enabled: true
policies:
camera: [] # Disable camera
microphone: ['self'] # Allow microphone for same origin only
geolocation: ['self', 'https://trusted.com']
fullscreen: ['*'] # Allow all origins
```
--------------------------------
### Example: Get Supported CSP Directives
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/policy-manager.md
Demonstrates how to use PolicyManager to get the CSP directives supported by a specific browser's User-Agent.
```php
$policyManager = new PolicyManager($uaParser);
$request = new Request();
$request->headers->set('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');
$supported = $policyManager->getAvailableDirective($request);
// Result: ['default-src', 'base-uri', 'block-all-mixed-content', ..., all modern directives]
```
--------------------------------
### Complete Security Configuration Example
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/configuration.md
A comprehensive example of Nelmio Security Bundle configuration, including signed cookies, clickjacking protection, external redirects, SSL enforcement, CSP, and more.
```yaml
nelmio_security:
signed_cookie:
names: ['auth', 'remember_me']
secret: '%kernel.secret%'
hash_algo: 'sha256'
separator: '.'
clickjacking:
paths:
'^/.*': { header: 'DENY' }
'^/api/.*': { header: 'ALLOW' }
external_redirects:
abort: false
allow_list:
- 'https://trusted-partner.com'
forced_ssl:
enabled: true
hsts_max_age: 31536000
hsts_subdomains: true
hsts_preload: true
content_type:
nosniff: true
csp:
enabled: true
enforce:
default-src: ["'self'"]
script-src: ["'self'", "https://trusted-cdn.com"]
style-src: ["'self'"]
img-src: ["'self'", "https:", "data:"]
referrer_policy:
enabled: true
policies: ['no-referrer', 'strict-origin-when-cross-origin']
permissions_policy:
enabled: true
policies:
camera: []
microphone: []
geolocation: ['self']
cross_origin_isolation:
enabled: true
paths:
'^/.*':
coep: 'require-corp'
coop: 'same-origin'
corp: 'same-origin'
```
--------------------------------
### Example CSP Policy Configuration
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/configuration.md
A comprehensive example of defining CSP directives for enforcement, including source lists and specific directives like frame-ancestors.
```yaml
nelmio_security:
csp:
enforce:
level1_fallback: true
default-src: ["'self'"]
script-src:
- "'self'"
- "https://trusted-cdn.com"
- "https://js.example.com"
style-src:
- "'self'"
- "'unsafe-inline'"
img-src:
- "'self'"
- "https:"
- "data:"
connect-src:
- "'self'"
- "https://api.example.com"
font-src:
- "'self'"
- "https://fonts.googleapis.com"
base-uri: ["'self'"]
form-action: ["'self'"]
frame-ancestors: ["'none'"]
block-all-mixed-content: true
upgrade-insecure-requests: true
```
--------------------------------
### Configure Referrer Policy
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/src/Resources/doc/index.rst
Example of configuring multiple referrer policies. The order is important as browsers select the last understood policy.
```yaml
nelmio_security:
referrer_policy:
enabled: true
policies:
- 'no-referrer'
- 'strict-origin-when-cross-origin'
```
--------------------------------
### CSP Header Example
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/sha-computer.md
An example of how a computed SHA hash is used within a Content Security Policy header to allow specific inline scripts.
```html
Content-Security-Policy: script-src 'sha256-abc123...'
```
--------------------------------
### CSP Header Example
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/nonce-generator.md
An example of a Content Security Policy header that includes a nonce directive, allowing scripts with the specified nonce to execute.
```http
Content-Security-Policy: script-src 'nonce-abc123...'
```
--------------------------------
### Complete Security Headers Test Example
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/test-assertions.md
A comprehensive example demonstrating how to use various NelmioSecurityBundle assertions within a Symfony WebTestCase. This includes assertions for CSP, frame options, content type sniffing, referrer policy, HTTPS enforcement, and cross-origin isolation.
```php
use Nelmio\SecurityBundle\Test\SecurityHeadersAssertionsTrait;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class SecurityHeadersTest extends WebTestCase
{
use SecurityHeadersAssertionsTrait;
public function testHomePageSecurityHeaders(): void
{
$client = static::createClient([], ['HTTPS' => 'on']);
$client->request('GET', '/');
// Assert CSP
static::assertCspHeader(
requiredDirectives: ['default-src', 'script-src'],
contains: ["'self'"],
notContains: ["'unsafe-inline'"]
);
// Assert clickjacking protection
static::assertFrameOptions('DENY');
// Assert content type sniffing protection
static::assertContentTypeOptions();
// Assert referrer policy
static::assertReferrerPolicy(['no-referrer']);
// Assert HTTPS enforcement
static::assertStrictTransportSecurity();
// Assert cross-origin isolation
static::assertIsIsolated();
}
}
```
--------------------------------
### Twig CSP Tag Syntax Example
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/errors.md
Demonstrates the correct syntax for the {% csp_script %} Twig tag, including the required algorithm parameter.
```twig
{% csp_script %} {# Missing algorithm parameter #}
code
{% endcsp_script %}
```
```twig
{% csp_script 'sha256' %} {# Correct syntax #}
code
{% endcsp_script %}
```
--------------------------------
### Basic Permissions Policy Configuration
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/src/Resources/doc/index.rst
Sets up the Permissions-Policy header to control web platform features. This example disables the camera, allows microphone for the same origin, and permits geolocation for all origins.
```yaml
nelmio_security:
permissions_policy:
enabled: true
policies:
payment: default
camera: []
microphone: ['self']
geolocation: ['*']
payment: ['self', 'https://payments.example.com']
```
--------------------------------
### Custom User-Agent Parser Implementation
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/policy-manager.md
Provides an example of implementing a custom UserAgentParserInterface for integrating alternative user-agent parsing libraries.
```php
class CustomUAParser implements UserAgentParserInterface
{
public function getBrowser(string $userAgent): string
{
// Return UserAgentParserInterface::BROWSER_* constants
}
}
```
--------------------------------
### Allowed Redirect Example
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/external-redirect.md
Demonstrates a successful redirect when the target URL's host is present in the configured allow-list. The bundle will automatically create an `ExternalRedirectResponse`.
```php
return $this->redirect('https://trusted.com/callback');
// Response: 302 redirect to trusted.com/callback
```
--------------------------------
### Request Matching Configuration
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/csp-listener.md
Example configuration for applying CSP only to requests matching a custom RequestMatcherInterface. The listener checks the matcher.
```yaml
nelmio_security:
csp:
request_matcher: 'my_custom_matcher'
```
```php
if (null !== $this->requestMatcher && !$this->requestMatcher->matches($request)) {
return; // Skip CSP for this request
}
```
--------------------------------
### Install NelmioSecurityBundle
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/README.md
Use Composer to require the nelmio/security-bundle package. The bundle is typically auto-enabled with Symfony Flex.
```bash
composer require nelmio/security-bundle
```
--------------------------------
### CSP Configuration: Avoid 'unsafe-inline'
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/twig-integration.md
Example of a bad CSP configuration that uses 'unsafe-inline', which defeats the purpose of CSP. Avoid this configuration.
```yaml
nelmio_security:
csp:
enforce:
script-src: ["'self'", "'unsafe-inline'"]
```
--------------------------------
### CSP Configuration: Enable CSP
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/twig-integration.md
Example of enabling the CSP feature in Nelmio Security Bundle configuration. Ensure CSP is enabled for nonces to be generated and used.
```yaml
nelmio_security:
csp:
enabled: true # Ensure enabled
hosts: [] # Empty = all hosts
content_types: [] # Empty = all types
```
--------------------------------
### Generated Permissions-Policy Header
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/src/Resources/doc/index.rst
The resulting Permissions-Policy HTTP header generated from the basic configuration example.
```text
Permissions-Policy: camera=(), microphone=(self), geolocation=(*), payment=(self "https://payments.example.com")
```
--------------------------------
### CSP Reporting Configuration Example
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/src/Resources/doc/index.rst
Configuration for CSP that only reports violations without enforcing the policy, specifically for JavaScript source restrictions.
```yaml
report:
# see full description below
level1_fallback: true
# only send directives supported by the browser, defaults to false
# this is a port of https://github.com/twitter/secureheaders/blob/83a564a235c8be1a8a3901373dbc769da32f6ed7/lib/secure_headers/headers/policy_management.rb#L97
browser_adaptive:
enabled: true
report-uri: '%router.request_context.base_url%/my-csp-report'
script-src:
- 'self'
```
--------------------------------
### Use Nonces for Dynamic Script Content
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/twig-integration.md
Example demonstrating the best practice of using `csp_nonce` for scripts whose content varies per request, such as those including dynamic user IDs or CSRF tokens. This ensures that dynamically generated content is securely executed.
```twig
```
--------------------------------
### Example CSP Report JSON
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/errors.md
This is the expected JSON format for a Content Security Policy report.
```json
{
"csp-report": {
"document-uri": "...",
"violated-directive": "..."
}
}
```
--------------------------------
### CSP Configuration: Enforce Script Source with Nonce
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/twig-integration.md
Example of enforcing script-src in CSP using a nonce. This is the recommended approach for dynamic content.
```yaml
nelmio_security:
csp:
enforce:
script-src: ["'self'", "https://trusted.com"]
```
--------------------------------
### Setup SecurityHeadersAssertionsTrait in a Test Class
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/test-assertions.md
Include the `SecurityHeadersAssertionsTrait` in your test class that extends `WebTestCase` to gain access to security header assertions.
```php
use Nelmio\SecurityBundle\Test\SecurityHeadersAssertionsTrait;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class MyControllerTest extends WebTestCase
{
use SecurityHeadersAssertionsTrait;
}
```
--------------------------------
### Twig: Inline Script with Nonce
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/twig-integration.md
Example of a small, critical inline script in Twig that uses a nonce. Inline scripts should be kept minimal.
```twig
```
--------------------------------
### Twig: Multiple Script Tags with Individual Hashes
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/twig-integration.md
Example demonstrating how to use multiple `csp_script` tags in Twig. Each tag computes its own hash, which is the correct approach.
```twig
{# ✓ Each tag gets its own hash #}
{% csp_script 'sha256' %}code1{% endcsp_script %}
{% csp_script 'sha256' %}code2{% endcsp_script %}
```
--------------------------------
### Blocked Redirect with Override Example
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/external-redirect.md
Shows how a blocked redirect can be handled by redirecting to a safe, predefined URL when the `override` option is configured. The original untrusted URL is not followed.
```php
return $this->redirect('https://untrusted.com');
// Response: 302 redirect to /redirect-error
```
--------------------------------
### Blocked Redirect with Forward As Example
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/external-redirect.md
Demonstrates redirecting to an override URL while also forwarding the original untrusted URL as a query parameter, using the `forward_as` configuration option. This is useful for displaying error messages or confirmation pages.
```php
return $this->redirect('https://untrusted.com/callback');
// Response: 302 redirect to /redirect-confirmation?target_url=https%3A%2F%2Funtrusted.com%2Fcallback
```
--------------------------------
### Test API Endpoint with Relaxed COR P
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/TESTING.md
This example shows how to test an API endpoint that might have a more relaxed `Cross-Origin-Resource-Policy` (e.g., 'cross-origin') compared to other parts of the application.
```php
public function testApiEndpointHasRelaxedCORP(): void
{
$client = static::createClient([], ['HTTPS' => 'on']);
$client->request('GET', '/api/public/data');
// API might use 'cross-origin' instead of 'same-origin'
static::assertCrossOriginHeaders('cross-origin', 'require-corp', 'same-origin');
}
```
--------------------------------
### Get Script Sample
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/csp-violation-report.md
Retrieve a sample of the inline script that was blocked. The `getScriptSample` method returns the first 40 characters of the `script-sample` field.
```php
$report = new Report([
'script-sample' => "console.log('evil'); window.l..."
]);
echo $report->getScriptSample(); // Output: "console.log('evil'); window.l..."
```
--------------------------------
### Twig: Correct Inline Script Content for Hash
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/twig-integration.md
Example of a correctly formatted inline script for hash computation in Twig. The content must exactly match the computed hash.
```twig
{# ✓ Correct - exact content #}
{% csp_script 'sha256' %}
console.log('test');
{% endcsp_script %}
```
--------------------------------
### Blocked Redirect with Abort Example
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/external-redirect.md
Illustrates a blocked redirect when the target URL is not in the allow-list and the `abort` configuration is set to `true`. An `InvalidArgumentException` will be thrown.
```php
return $this->redirect('https://untrusted.com');
// Throws: InvalidArgumentException (if abort: true)
```
--------------------------------
### Dynamic Inline Script with CSP Nonce
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/README.md
This example shows how to embed a dynamic inline script in Twig, using a CSP nonce to allow execution while adhering to security policies. It includes application configuration data.
```twig
```
--------------------------------
### Configure CSP Report Filters
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/csp-violation-report.md
Configure various noise detectors to filter out common false-positive CSP violations in the bundle configuration. This example enables domain and scheme filtering.
```yaml
nelmio_security:
csp:
report_endpoint:
filters:
domains: true
schemes: true
browser_bugs: true
injected_scripts: true
dismiss:
script-src:
- 'https://analytics.google.com'
style-src:
- '*'
```
--------------------------------
### Twig: Multiple Inline Scripts with Same Nonce
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/twig-integration.md
Example showing multiple inline script tags in Twig using the same nonce. This is the correct behavior as the nonce validates all scripts using it within a request.
```twig
{# ✓ Use different nonces for different tags #}
```
--------------------------------
### Example CSP Violation Report Payload
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/csp-violation-report.md
This is an example of the JSON payload that browsers send as a CSP violation report to the configured report endpoint.
```json
POST /_/csp-report HTTP/1.1
Content-Type: application/json
{
"csp-report": {
"document-uri": "https://example.com/page",
"violated-directive": "script-src 'self'",
"effective-directive": "script-src",
"blocked-uri": "https://malicious.com/evil.js",
"original-policy": "script-src 'self'; report-uri /_/csp-report",
"disposition": "enforce"
}
}
```
--------------------------------
### Common Permissions Policy Settings
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/src/Resources/doc/index.rst
A comprehensive example of common Permissions-Policy configurations, including media, privacy, and display features. This snippet disables FLoC tracking and allows specific origins for payment and credential requests.
```yaml
nelmio_security:
permissions_policy:
enabled: true
policies:
camera: []
microphone: []
geolocation: []
accelerometer: []
gyroscope: []
magnetometer: []
interest_cohort: []
payment: ['self']
publickey_credentials_get: ['self']
fullscreen: ['self']
picture_in_picture: ['self']
autoplay: []
```
--------------------------------
### Enable CSP in Nelmio Security Configuration
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/twig-integration.md
Configure the Nelmio Security Bundle to enable CSP by setting `csp.enabled` to `true` and defining the `enforce` directives for 'script-src' and 'style-src'. This setup is necessary for the Twig CSP functions and tags to operate correctly.
```yaml
nelmio_security:
csp:
enabled: true # Default is true
enforce:
script-src: ["'self'"]
style-src: ["'self'"]
hash:
algorithm: 'sha256'
```
--------------------------------
### Constructor
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/csp-violation-report.md
Initializes a new instance of the Report class. It accepts an array of CSP report data and an optional User-Agent string.
```APIDOC
## Constructor
### Description
Initializes a new instance of the Report class. It accepts an array of CSP report data and an optional User-Agent string.
### Signature
```php
public function __construct(array $data = [], ?string $userAgent = null): void
```
### Parameters
#### Parameters
- **$data** (array) - Optional - CSP report data fields (see Report Data Fields below)
- **$userAgent** (string|null) - Optional - User-Agent string of the client that triggered the violation
### Example
```php
$data = [
'document-uri' => 'https://example.com/page',
'violated-directive' => 'script-src',
'blocked-uri' => 'https://malicious.com/script.js',
'effective-directive' => 'script-src',
];
$report = new Report($data, $_SERVER['HTTP_USER_AGENT'] ?? null);
```
```
--------------------------------
### Instantiate ShaComputer
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/sha-computer.md
Create a new ShaComputer instance by specifying the desired hash algorithm. Supported algorithms are 'sha256', 'sha384', and 'sha512'.
```php
use Nelmio\SecurityBundle\ContentSecurityPolicy\ShaComputer;
$computer = new ShaComputer('sha256');
```
--------------------------------
### Algorithm Migration Strategy
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/signer.md
Configure both primary and legacy algorithms to allow seamless migration to a stronger hashing algorithm. Deploy with both, then remove the legacy option after all users have updated cookies.
```text
# 1. Deploy with both algorithms configured:
# hash_algo: sha256 (primary)
# legacy_hash_algo: sha1 (fallback)
#
# 2. The signer accepts both SHA1-signed and SHA256-signed cookies
#
# 3. Browser receives new cookies with SHA256 signatures
#
# 4. Once all users have renewed cookies (typically within session lifetime), remove legacy_hash_algo
```
--------------------------------
### Enforced Content-Security-Policy Header
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/csp-listener.md
Example of an enforced Content-Security-Policy header. Violations are blocked by the browser.
```http
Content-Security-Policy: script-src 'self' 'nonce-abc123'; style-src 'self'; ...
```
--------------------------------
### Simple COEP and COOP Configuration
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/src/Resources/doc/index.rst
Use this simple string format for basic COEP and COOP configurations without reporting.
```yaml
coep: require-corp
coop: same-origin
```
--------------------------------
### Report-Only Content-Security-Policy Header
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/csp-listener.md
Example of a Content-Security-Policy-Report-Only header. Violations are reported but not blocked, useful for testing.
```http
Content-Security-Policy-Report-Only: script-src 'self'; style-src 'self'; ...
```
--------------------------------
### Get Directive Set Builders
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/csp-listener.md
Returns the directive set builders for both enforce and report policies.
```php
public function getDirectiveSetBuilders(): array
```
--------------------------------
### Constructor
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/csp-listener.md
Initializes the ContentSecurityPolicyListener with various builders, generators, and configuration options.
```APIDOC
## Constructor
### Description
Initializes the ContentSecurityPolicyListener with various builders, generators, and configuration options.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **`$reportDirectiveSetBuilder`** (`DirectiveSetBuilderInterface`|`DirectiveSet`) - Required - Builder for CSP report-only policy
- **`$enforceDirectiveSetBuilder`** (`DirectiveSetBuilderInterface`|`DirectiveSet`) - Required - Builder for enforced CSP policy
- **`$nonceGenerator`** (`NonceGeneratorInterface`) - Required - Generator for CSP nonces
- **`$shaComputer`** (`ShaComputerInterface`) - Required - Computer for inline script/style hashes
- **`$compatHeaders`** (`bool`) - Optional - Send webkit-prefixed headers for older iOS. Default: `true`
- **`$hosts`** (`string[]`) - Optional - Host names to apply CSP to. Empty = all hosts. Default: `[]`
- **`$contentTypes`** (`string[]`) - Optional - Content types to apply CSP to. Empty = all types. Default: `[]`
- **`$requestMatcher`** (`RequestMatcherInterface`|`null`) - Optional - Custom request matcher for conditional CSP. Default: `null`
```
--------------------------------
### Configure CSP with Nonces
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/README.md
Sets up Content Security Policy with default, script, and style sources, enabling nonce generation for inline scripts.
```yaml
nelmio_security:
csp:
enforce:
default-src: ["'self'"]
script-src: ["'self'"]
style-src: ["'self'"]
```
--------------------------------
### Enable Content Security Policy (CSP)
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/configuration.md
Basic configuration to enable CSP with compatibility headers and specify a logger service.
```yaml
nelmio_security:
csp:
enabled: true
compat_headers: true
report_logger_service: 'logger'
request_matcher: null
hosts: []
content_types: []
hash:
algorithm: 'sha256'
report_endpoint:
log_channel: null
log_formatter: 'nelmio_security.csp_report.log_formatter'
log_level: 'notice'
filters:
domains: true
schemes: true
browser_bugs: true
injected_scripts: true
dismiss: {}
enforce:
level1_fallback: true
browser_adaptive:
enabled: false
parser: 'nelmio_security.ua_parser.ua_php'
default-src: ["'self'"]
script-src: ["'self'"]
# ... other directives
```
--------------------------------
### Signer Constructor
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/signer.md
Initializes the Signer with a secret key, primary algorithm, optional legacy algorithm, and separator. Ensure the specified algorithms are supported by the system.
```php
public function __construct(
string $secret,
string $algo,
?string $legacyAlgo = null,
string $separator = '.'
): void
```
--------------------------------
### External Redirect with Global Allow List
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/src/Resources/doc/index.rst
Demonstrates using an external redirect with a global allow list configured in the security settings.
```yaml
nelmio_security:
external_redirects:
abort: true
allow_list:
- bar.com
```
--------------------------------
### Configure All Cookies to be Signed
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/src/Resources/doc/index.rst
Use '*' to sign all cookies. Be aware this can impact login functionality. Use with caution.
```yaml
nelmio_security:
signed_cookie:
names: ['*']
```
--------------------------------
### Get Supported Directive Names
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/directive-set.md
The `getNames` static method returns a map of all supported directive names to their corresponding type constants.
```php
public static function getNames(): array
{
// ... implementation details ...
}
```
--------------------------------
### Create DirectiveSet from Configuration
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/directive-set.md
Use the `fromConfig` static factory method to create a DirectiveSet instance based on bundle configuration. Specify whether to build an enforce or report policy.
```php
public static function fromConfig(
PolicyManager $policyManager,
array $config,
string $kind
): self
{
// ... implementation details ...
}
```
```php
$directiveSet = DirectiveSet::fromConfig($policyManager, $config, 'enforce');
```
--------------------------------
### Get Blocked Resource URI
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/csp-violation-report.md
Retrieve the URL of the resource that was blocked by the CSP. Use the `getUri` method to access the `blocked-uri` field.
```php
echo $report->getUri(); // Output: "https://malicious.com/script.js"
```
--------------------------------
### Get Violated CSP Directive
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/csp-violation-report.md
Retrieve the CSP directive that was violated. The `getDirective` method prioritizes `effective-directive` and falls back to `violated-directive`.
```php
$report = new Report([
'effective-directive' => 'script-src',
'blocked-uri' => 'https://cdn.example.com/lib.js',
]);
echo $report->getDirective(); // Output: "script-src"
```
--------------------------------
### ShaComputer Constructor
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/sha-computer.md
Initializes the ShaComputer with a specified hash algorithm. Throws an InvalidArgumentException if the algorithm is not supported.
```APIDOC
## ShaComputer Constructor
### Description
Initializes the ShaComputer with a specified hash algorithm.
### Method
`__construct(string $type)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **$type** (string) - Required - Hash algorithm: 'sha256', 'sha384', or 'sha512'
### Throws
- `InvalidArgumentException` if type is not one of the supported algorithms
### Example
```php
$computer = new ShaComputer('sha256');
```
```
--------------------------------
### Clickjacking Protection Applied to Specific Hosts
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/src/Resources/doc/index.rst
Restricts clickjacking protection rules to apply only to specified host patterns. Useful for multi-domain setups.
```yaml
nelmio_security:
clickjacking:
paths:
'^/iframes/': ALLOW
'^/.*': DENY
content_types: []
hosts:
- '^foo\.com$'
- '\.example\.org$'
```
--------------------------------
### Signer Constructor
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/signer.md
Initializes the Signer with a secret key, hash algorithm, and optional legacy algorithm and separator.
```APIDOC
## Signer Constructor
### Description
Initializes the Signer with a secret key, hash algorithm, and optional legacy algorithm and separator.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **`$secret`** (string) - Required - The secret key used for HMAC computation
- **`$algo`** (string) - Required - Primary hash algorithm (e.g., `sha256`, `sha512`). Must be in `hash_algos()`
- **`$legacyAlgo`** (string|null) - Optional - Legacy algorithm for backward compatibility during migration. If provided, verifies signatures against both primary and legacy algorithms. Defaults to `null`.
- **`$separator`** (string) - Optional - Character(s) separating the value from the signature in signed values. Defaults to `'.'`.
### Throws
- `InvalidArgumentException` if `$algo` is not supported by the system
- `InvalidArgumentException` if `$legacyAlgo` is specified but not supported by the system
```
--------------------------------
### Use Hashes for Static CSS Content
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/twig-integration.md
Illustrates the best practice of using `csp_style` with a hash algorithm for static CSS content that remains consistent across all requests. This approach is suitable for critical CSS that does not change.
```twig
{% csp_style 'sha256' %}
/* Critical CSS - same for all users */
body { margin: 0; }
{% endcsp_style %}
```
--------------------------------
### Get Domain from Blocked URI
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/csp-violation-report.md
Extract the domain name from the blocked resource's URL. The `getDomain` method handles parsing the `blocked-uri` field.
```php
$report = new Report(['blocked-uri' => 'https://cdn.malicious.com:443/lib.js?v=1']);
echo $report->getDomain(); // Output: "cdn.malicious.com"
```
--------------------------------
### Browser Adaptive CSP with Custom Cache Parser
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/src/Resources/doc/index.rst
Configures browser adaptive CSP with a custom cache parser service to optimize CPU usage. Requires defining 'my_own_parser' service.
```yaml
# config/packages/nelmio_security.yaml
nelmio_security:
csp:
enforce:
browser_adaptive:
enabled: true
parser: my_own_parser
```
--------------------------------
### Twig: Large Inline Script (Bad Practice)
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/twig-integration.md
Example of a large inline script in Twig, which is considered bad practice. Large scripts should be moved to external files.
```twig
```
--------------------------------
### Test Security Headers for Multiple Routes
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/TESTING.md
Demonstrates how to test security headers across multiple routes using a data provider. This ensures consistent security configurations for different parts of your application.
```php
/**
* @dataProvider routeProvider
*/
public function testSecurityHeadersForAllRoutes(string $route):
{
$client = static::createClient([], ['HTTPS' => 'on']);
$client->request('GET', $route);
static::assertIsIsolated();
static::assertFrameOptions('DENY');
static::assertContentTypeOptions();
}
public static function routeProvider(): iterable
{
yield 'homepage' => ['/'];
yield 'about' => ['/about'];
yield 'contact' => ['/contact'];
}
```
--------------------------------
### Constructor
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/directive-set.md
Initializes a new DirectiveSet instance. It requires a PolicyManager to handle browser-adaptive directive filtering.
```APIDOC
## Constructor
```php
public function __construct(PolicyManager $policyManager): void
```
### Parameters
- **$policyManager** (PolicyManager) - Policy manager for browser-adaptive directive filtering
```
--------------------------------
### Enable Basic Security Headers
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/README.md
Enables basic security headers like Content-Type nosniff, Clickjacking protection with DENY, Referrer-Policy, and Forced SSL with HSTS.
```yaml
nelmio_security:
content_type:
nosniff: true
clickjacking:
paths:
'^/.*': { header: 'DENY' }
referrer_policy:
enabled: true
forced_ssl:
enabled: true
hsts_max_age: 31536000
```
--------------------------------
### onKernelRequest Method
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/csp-listener.md
Processes incoming requests to initialize CSP state for the current request. It only processes main requests and resets per-request state.
```php
public function onKernelRequest(RequestEvent $e): void
```
--------------------------------
### Alert on Specific CSP Violations
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/csp-violation-report.md
Implement custom logic to alert on specific CSP violations, such as unexpected script sources from untrusted domains. This example checks the directive and domain.
```php
if ($report->getDirective() === 'script-src' && !str_contains($report->getDomain() ?? '', 'trusted.com')) {
// Alert: Unexpected script source
}
```
--------------------------------
### Integration with DirectiveSetBuilder
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/csp-listener.md
Demonstrates how the listener uses DirectiveSetBuilders to construct CSP policies. Configure builders in the bundle config.
```php
// Configure in bundle config
$enforceDirectives = $enforceBuilder->getDirectiveSet($request);
$reportDirectives = $reportBuilder->getDirectiveSet($request);
// Listener builds headers from these
$enforceHeader = $enforceDirectives->buildHeaderValue($request, $signatures);
$reportHeader = $reportDirectives->buildHeaderValue($request);
```
--------------------------------
### Custom User Agent Parser Service Definition
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/src/Resources/doc/index.rst
Example XML service definition for a custom user agent parser using PsrCacheUAFamilyParser, integrating with application cache and UA parser services.
```xml
604800
```
--------------------------------
### onKernelRequest
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/csp-listener.md
Processes incoming requests to initialize CSP state for the request. It resets per-request state and only processes main requests.
```APIDOC
## onKernelRequest
### Description
Processes incoming requests to initialize CSP state for the request. It resets per-request state and only processes main requests.
### Method
`onKernelRequest`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **`$e`** (`RequestEvent`) - Required - Kernel request event
### Behavior:
- Resets per-request state (nonces, hashes)
- Only processes main requests (ignores subrequests)
```
--------------------------------
### Get Verified Raw Value from Signed Cookie
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/signer.md
Verifies a signed value and returns the original, unsigned data. Throws an InvalidArgumentException if the signature is not valid. Use this to safely retrieve cookie data.
```php
$signer = new Signer('my-secret', 'sha256');
try {
$value = $signer->getVerifiedRawValue($_COOKIE['auth']);
} catch (InvalidArgumentException $e) {
// Invalid signature
}
```
--------------------------------
### Maximum Security Configuration Example
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/src/Resources/doc/index.rst
This configuration provides the highest level of security protection for your Symfony application. It includes settings for signed cookies, clickjacking protection, external redirects, and content security policy.
```yaml
# config/packages/nelmio_security.yaml
nelmio_security:
# signs/verifies all cookies
signed_cookie:
names: ['*'] # Beware: Login won't work if all cookies are signed.
# prevents framing of the entire site
clickjacking:
paths:
'^/.*': DENY
hosts:
- '^foo\.com$'
- '\.example\.org$'
# prevents redirections outside the website's domain
external_redirects:
abort: true
log: true
# prevents inline scripts, unsafe eval, external scripts/images/styles/frames, etc
csp:
hosts: []
content_types: []
enforce:
level1_fallback: false
browser_adaptive:
enabled: false
report-uri: '%router.request_context.base_url%/my-csp-report'
default-src:
- 'none'
script-src:
- 'self'
```
--------------------------------
### Deprecated XSS Protection vs. Recommended CSP
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/README.md
Shows the deprecated `xss_protection` configuration and the recommended CSP alternative without `unsafe-inline`.
```yaml
# ✗ Deprecated
nelmio_security:
xss_protection:
enabled: true
# ✓ Recommended
nelmio_security:
csp:
enforce:
script-src: ["'self'"] # No 'unsafe-inline'
```
--------------------------------
### Twig: Incorrect Inline Script Content for Hash
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/twig-integration.md
Example of an incorrectly formatted inline script for hash computation in Twig. Using template variables that modify the content will lead to hash mismatch errors.
```twig
{# ✗ Wrong - content is modified #}
{% set code = "console.log('test');" %}
{% csp_script 'sha256' %}
{{ code }}
{% endcsp_script %}
```
--------------------------------
### Twig: Compute Script Hash with UTF-8 Encoding
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/twig-integration.md
Example of computing a script hash using the `csp_script` Twig function. Ensure the template encoding matches the hash computation encoding (e.g., UTF-8).
```twig
{# If hash is computed with UTF-8, template must be UTF-8 #}
{% csp_script 'sha256' %}
// UTF-8 content
{% endcsp_script %}
```
--------------------------------
### CSP Nonce Generation with ContentSecurityPolicyListener
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/src/Resources/doc/index.rst
For non-Twig environments, the ContentSecurityPolicyListener provides methods to get a nonce for script or style elements. It generates a nonce on the first call and reuses it for subsequent calls within the same request.
```php
// generates a nonce at first time, returns the same nonce once generated
$listener->getNonce('script');
// or
$listener->getNonce('style');
```
--------------------------------
### Handle Unknown CSP Directive in DirectiveSet
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/errors.md
Catch InvalidArgumentException when attempting to set or get an unknown CSP directive using DirectiveSet::setDirective() or DirectiveSet::getDirective(). Use a valid CSP directive name.
```php
try {
$directiveSet->setDirective('unknown-directive', "'self'");
} catch (InvalidArgumentException $e) {
// Unknown CSP directive
}
```
--------------------------------
### Allow-list Configuration: Full URL
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/external-redirect.md
Configures the allow-list to only permit redirects to the exact, full URL specified, including the protocol.
```yaml
allow_list:
- 'https://example.com'
```
--------------------------------
### Get Available CSP Directives for a Request
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/policy-manager.md
Retrieves the list of CSP directives supported by the browser making the HTTP request. It inspects the User-Agent header to filter directives based on CSP level support.
```php
public function getAvailableDirective(Request $request): array
```
--------------------------------
### Assert X-Frame-Options Header
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/test-assertions.md
Checks if the `X-Frame-Options` header is set to the expected value, controlling how your site can be framed. Use 'DENY' to prevent all framing or 'SAMEORIGIN' to allow framing only from your own site.
```php
static::assertFrameOptions('SAMEORIGIN'); // Allow framing from same origin
static::assertFrameOptions('DENY'); // Prevent all framing
```
--------------------------------
### Instantiate CSP Violation Report
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/csp-violation-report.md
Create a new `Report` instance by passing an array of violation data and an optional User-Agent string. This is useful for manually creating reports or processing raw data.
```php
$data = [
'document-uri' => 'https://example.com/page',
'violated-directive' => 'script-src',
'blocked-uri' => 'https://malicious.com/script.js',
'effective-directive' => 'script-src',
];
$report = new Report($data, $_SERVER['HTTP_USER_AGENT'] ?? null);
```
--------------------------------
### Clickjacking Protection with Allow List Configuration
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/src/Resources/doc/index.rst
Configures specific paths to allow framing or specific origins, while denying all others. Useful for sites with framed content.
```yaml
nelmio_security:
clickjacking:
paths:
'^/iframes/': ALLOW
'^/business/': 'ALLOW-FROM https://biz.example.org'
'^/local/': SAMEORIGIN
'^/.*': DENY
content_types: []
hosts: []
```
--------------------------------
### Twig: Inline Scripts with Same Nonce (Correct Behavior)
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/twig-integration.md
Demonstrates that multiple inline scripts within the same request correctly receive and use the same nonce generated by `csp_nonce()`. This is expected behavior.
```twig
```
--------------------------------
### ContentSecurityPolicyListener Constructor
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/csp-listener.md
Initializes the listener with various builders, generators, and configuration options for CSP policies.
```php
public function __construct(
DirectiveSetBuilderInterface|DirectiveSet $reportDirectiveSetBuilder,
DirectiveSetBuilderInterface|DirectiveSet $enforceDirectiveSetBuilder,
NonceGeneratorInterface $nonceGenerator,
ShaComputerInterface $shaComputer,
bool $compatHeaders = true,
array $hosts = [],
array $contentTypes = [],
?RequestMatcherInterface $requestMatcher = null
): void
```
--------------------------------
### Configure Referrer Policy
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/configuration.md
Configuration to enable and define accepted policies for the Referrer-Policy header.
```yaml
nelmio_security:
referrer_policy:
enabled: false
policies:
- 'no-referrer'
- 'no-referrer-when-downgrade'
```
--------------------------------
### CSP Nonce Usage in HTML
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/nonce-generator.md
Demonstrates how to apply a generated nonce to script and style tags to allow their execution under a Content Security Policy. The nonce attribute must match the value specified in the CSP header.
```html
```
--------------------------------
### Rename forced_ssl.whitelist to allow_list
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/UPGRADE-2.12.md
Update your configuration to use `allow_list` instead of `whitelist` for forced SSL.
```yaml
nelmio_security:
forced_ssl:
enabled: true
whitelist:
- ^/unsecure/
```
```yaml
nelmio_security:
forced_ssl:
enabled: true
allow_list:
- ^/unsecure/
```
--------------------------------
### Generic Exception Handling in PHP
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/errors.md
Shows how to catch various Nelmio Security Bundle exceptions, including generic violation exceptions, invalid arguments, and type errors.
```php
use Nelmio\SecurityBundle\ContentSecurityPolicy\Violation\Exception\ExceptionInterface;
try {
// Bundle operations
} catch (ExceptionInterface $e) {
// Handle bundle-specific violation exceptions
} catch (InvalidArgumentException $e) {
// Handle invalid configuration/input
} catch (TypeError $e) {
// Handle type errors
}
```
--------------------------------
### PolicyManager Constructor
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/policy-manager.md
Instantiates the PolicyManager. An optional UserAgentParserInterface can be provided; otherwise, it defaults to Chrome directives.
```php
public function __construct(?UserAgentParserInterface $uaParser = null): void
```
--------------------------------
### Allow-list Configuration: Leading Wildcard
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/external-redirect.md
Configures the allow-list to permit redirects to any subdomain of a specified domain, but not the domain itself. The wildcard must be at the beginning of the entry.
```yaml
allow_list:
- '.example.com'
# Matches: https://sub.example.com, https://deep.sub.example.com
# Does not match: https://example.com (trailing domain) or https://exampleX.com
```
--------------------------------
### Configure CSP with Hashes
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/README.md
Configures Content Security Policy to use SHA256 hashing for inline scripts and styles, alongside self-source.
```yaml
nelmio_security:
csp:
hash:
algorithm: 'sha256'
enforce:
script-src: ["'self'"]
style-src: ["'self'"]
```
--------------------------------
### Test Cross-Origin Resource Policy with assertThat
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/TESTING.md
Demonstrates how to use NelmioSecurityBundle's custom constraints directly with PHPUnit's `assertThat()` method for granular testing of security headers like Cross-Origin-Resource-Policy.
```php
use Nelmio\SecurityBundle\Test\Constraint\ResponseHasCrossOriginResourcePolicy;
$response = $client->getResponse();
static::assertThat(
$response,
new ResponseHasCrossOriginResourcePolicy('same-origin')
);
```
--------------------------------
### PolicyManager Constructor
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/policy-manager.md
Initializes the PolicyManager. An optional UserAgentParserInterface can be provided for browser detection; otherwise, it defaults to Chrome directives.
```APIDOC
## PolicyManager Constructor
### Description
Initializes the PolicyManager. An optional UserAgentParserInterface can be provided for browser detection; otherwise, it defaults to Chrome directives.
### Method
```php
public function __construct(?UserAgentParserInterface $uaParser = null): void
```
### Parameters
#### Path Parameters
- **$uaParser** (UserAgentParserInterface|null) - Required - User-agent parser for browser detection. If null, defaults to Chrome directives
```
--------------------------------
### Webkit-Prefixed CSP Headers
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/csp-listener.md
Generates X-WebKit-CSP and X-Content-Security-Policy headers for compatibility with older browsers when compat_headers is true.
```http
X-WebKit-CSP: ...
X-Content-Security-Policy: ...
```
--------------------------------
### Basic Security Headers Test
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/TESTING.md
This snippet demonstrates a basic functional test using `SecurityHeadersAssertionsTrait` to assert the presence and configuration of common security headers on the homepage.
```php
'on']);
$client->request(Request::METHOD_GET, '/');
static::assertIsIsolated();
static::assertFrameOptions('DENY');
static::assertContentTypeOptions();
static::assertReferrerPolicy(['no-referrer', 'strict-origin-when-cross-origin']);
static::assertStrictTransportSecurity();
static::assertCspHeader();
}
}
```
--------------------------------
### Assert All Cross-Origin Headers
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/TESTING.md
Asserts all cross-origin headers (`Cross-Origin-Resource-Policy`, `Cross-Origin-Embedder-Policy`, `Cross-Origin-Opener-Policy`) at once. All parameters are required.
```php
// All cross-origin headers at once (all parameters are required)
static::assertCrossOriginHeaders('same-origin', 'require-corp', 'same-origin');
```
--------------------------------
### Enable Logging for External Redirects
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/src/Resources/doc/index.rst
Configure the bundle to log external redirects at a warning level. This helps in identifying potential security risks or accidental redirects.
```yaml
nelmio_security:
external_redirects:
log: true
```
--------------------------------
### Assert Cross-Origin-Opener-Policy
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/test-assertions.md
Asserts that the Cross-Origin-Opener-Policy header has the expected value. The expected value can be 'same-origin', 'same-origin-allow-popups', 'unsafe-none', or 'noopener-allow-popups'.
```php
public static function assertCrossOriginOpenerPolicy(
string $expected = 'same-origin',
string $message = ''
): void
```
--------------------------------
### Instantiate NonceGenerator
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/nonce-generator.md
Create a NonceGenerator instance, specifying the number of random bytes to generate. A common recommendation is 16 bytes, which results in approximately a 24-character base64 encoded string.
```php
// Generate 16 random bytes, resulting in ~24 character base64 nonce
$generator = new NonceGenerator(16);
```
--------------------------------
### Configure Clickjacking Protection
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/configuration.md
Add X-Frame-Options header to prevent clickjacking attacks. Specify hosts, content types, and paths with associated frame options.
```yaml
nelmio_security:
clickjacking:
hosts: []
content_types: []
paths:
'^/.*': { header: 'DENY' }
```
```yaml
nelmio_security:
clickjacking:
paths:
'^/.*': { header: 'DENY' }
'^/api/.*': { header: 'ALLOW' }
'^/embed': { header: 'ALLOW-FROM https://trusted.com' }
```
--------------------------------
### getScriptSample
Source: https://github.com/nelmio/nelmiosecuritybundle/blob/master/_autodocs/api-reference/csp-violation-report.md
Returns a sample of the inline script that was blocked, limited to the first 40 characters by the browser.
```APIDOC
## getScriptSample
### Description
Returns the sample of inline script that was blocked. Limited to first 40 characters by the browser.
### Signature
```php
public function getScriptSample(): ?string
```
### Returns
- `string|null` — Script sample or null if not available
### Example
```php
$report = new Report([
'script-sample' => "console.log('evil'); window.l..."
]);
echo $report->getScriptSample(); // Output: "console.log('evil'); window.l..."
```
```