getNonces example

use Symfony\Component\HttpFoundation\Response;

class ContentSecurityPolicyHandlerTest extends TestCase
{
    /** * @dataProvider provideRequestAndResponses */
    public function testGetNonces($nonce$expectedNonce, Request $request, Response $response)
    {
        $cspHandler = new ContentSecurityPolicyHandler($this->mockNonceGenerator($nonce));

        $this->assertSame($expectedNonce$cspHandler->getNonces($request$response));
    }

    /** * @dataProvider provideRequestAndResponsesForOnKernelResponse */
    public function testOnKernelResponse($nonce$expectedNonce, Request $request, Response $response, array $expectedCsp)
    {
        $cspHandler = new ContentSecurityPolicyHandler($this->mockNonceGenerator($nonce));

        $this->assertSame($expectedNonce$cspHandler->updateResponseHeaders($request$response));

        

    public function updateResponseHeaders(Request $request, Response $response): array
    {
        if ($this->cspDisabled) {
            $this->removeCspHeaders($response);

            return [];
        }

        $nonces = $this->getNonces($request$response);
        $this->cleanHeaders($response);
        $this->updateCspHeaders($response$nonces);

        return $nonces;
    }

    private function cleanHeaders(Response $response): void
    {
        $response->headers->remove('X-SymfonyProfiler-Script-Nonce');
        $response->headers->remove('X-SymfonyProfiler-Style-Nonce');
    }

    
if (null === $this->profiler) {
            throw new NotFoundHttpException('The profiler must be enabled.');
        }

        $this->profiler->disable();
    }

    private function renderWithCspNonces(Request $request, string $template, array $variables, int $code = 200, array $headers = ['Content-Type' => 'text/html']): Response
    {
        $response = new Response('', $code$headers);

        $nonces = $this->cspHandler ? $this->cspHandler->getNonces($request$response) : [];

        $variables['csp_script_nonce'] = $nonces['csp_script_nonce'] ?? null;
        $variables['csp_style_nonce'] = $nonces['csp_style_nonce'] ?? null;

        $response->setContent($this->twig->render($template$variables));

        return $response;
    }
}
Home | Imprint | This part of the site doesn't use cookies.