Skip to content

Instantly share code, notes, and snippets.

@jaynzr
Created May 7, 2020 03:39
Show Gist options
  • Save jaynzr/ef4782d5f5b02befa45df650d379cb85 to your computer and use it in GitHub Desktop.
Save jaynzr/ef4782d5f5b02befa45df650d379cb85 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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment