CSP hash or nonce- dynamic generated in project


I have problem with generating hashes or nonce- attribute for script-src of my csp policy declared in layout header:


<html lang="en">
	<meta charset="utf-8">
	<?= $this->headTitle('Site title')->setSeparator(' - ')->setAutoEscape(false) ?>
	<?= $this->headMeta()
		->appendName('description', isset($description) ? $description : 'description default')
		->appendName('keywords', isset($keywords) ? $keywords : 'keywords default')
		->appendName('viewport', 'width=device-width, initial-scale=1.0')

		->appendHttpEquiv('X-UA-Compatible', 'IE=edge')
		->appendHttpEquiv('Content-Type', 'text/html; charset=UTF-8')
		->appendHttpEquiv('Content-Language', 'en-EN')

			"default-src 'none'; 
			script-src 'self' 'nonce-.......'; 
			connect-src 'self'; 
			font-src 'self';
			img-src 'self' blob:; 
			style-src 'self'; 
			base-uri 'self'; 
			form-action 'self'

and in template for example index.phtml:

< script nonce="…" >
// …
< /script >

How can I generate such a variable dynamically once for a request and pass it to the layout, templates? Has anyone faced a similar problem?

I will be grateful for every suggestion.


Hello and welcome to our forums! :smiley:

Do you have a Mezzio or laminas-mvc based application?


Laminas-mvc application.

Mayby onBootstrap generate nonce- base64_encode variable and sent to layout and template. Only how to pass a variable to be available in layout.phtml (header section) and each tamplate. Of course not in session.

Use a listener. There you have access to the view (layout), service-manager, request, route match and so on via the MVC event object. An example can be found in the documentation of laminas-view: “Cookbook: Setting module-specific Layouts

Thank you Frank for the tip.I set the variable with setVariable in OnBoostrap.
Code slice:

$layoutViewModel = $e->getViewModel();

// csp policy - generate nonce

$cspnNonce = base64_encode(…);

$layoutViewModel->setVariable(‘cspNonce’, $cspNonce);

But I’m not sure if it’s a good solution or not, it’s better to create the right class to support csp nonce-

Please pay attention to best practices when creating modules:

In your case this means that the variable does not have to be set for every request, only when rendering the layout. (e.g. redirects and output other than HTML)

Another option is to create a custom view helper.

Thank you very much.

I create view helper.

Best regards.