Skip to content

Instantly share code, notes, and snippets.

@jaynzr
Created May 7, 2020 03:39
Show Gist options
  • Save jaynzr/03a44b78264bc94eec2406ee34da42ed to your computer and use it in GitHub Desktop.
Save jaynzr/03a44b78264bc94eec2406ee34da42ed to your computer and use it in GitHub Desktop.
Extends Cake\Http\Middleware\CspMiddleware to support nonce.
<?php
namespace App\Middleware;
use Cake\Http\Middleware\CspMiddleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
class NonceCspMiddleware extends CspMiddleware
{
/**
* Serve assets if the path matches one. Generate nonce for <script>
*
* @param \Psr\Http\Message\ServerRequestInterface $request The request.
* @param \Psr\Http\Server\RequestHandlerInterface $handler The request handler.
* @return \Psr\Http\Message\ResponseInterface A response.
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$nonce = $this->csp->nonce('script-src');
$request = $request->withAttribute('cspScriptNonce', $nonce);
$response = $handler->handle($request);
// phpcs:ignore SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration.InvalidFormat
/** @var \Psr\Http\Message\ResponseInterface */
return $this->csp->injectCSPHeader($response);
}
}
@jaynzr
Copy link
Author

jaynzr commented May 7, 2020

Supports CakePHP v4.x

Add nonce attribute to all the <script> tags in your templates.
<script nonce="<?= $this->getRequest()->getAttribute('cspScriptNonce') ?>">

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment