Created
May 7, 2020 03:39
-
-
Save jaynzr/03a44b78264bc94eec2406ee34da42ed to your computer and use it in GitHub Desktop.
Extends Cake\Http\Middleware\CspMiddleware to support nonce.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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
Supports CakePHP v4.x
Add nonce attribute to all the <script> tags in your templates.
<script nonce="<?= $this->getRequest()->getAttribute('cspScriptNonce') ?>">