Created
May 7, 2020 03:39
-
-
Save jaynzr/ef4782d5f5b02befa45df650d379cb85 to your computer and use it in GitHub Desktop.
Extends Cake\Http\Middleware\CspMiddleware to support nonce.
This file contains 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