CsrfToken example

public function getToken(string $tokenId): CsrfToken
    {
        $namespacedId = $this->getNamespace().$tokenId;
        if ($this->storage->hasToken($namespacedId)) {
            $value = $this->storage->getToken($namespacedId);
        } else {
            $value = $this->generator->generateToken();

            $this->storage->setToken($namespacedId$value);
        }

        return new CsrfToken($tokenId$this->randomize($value));
    }

    public function refreshToken(string $tokenId): CsrfToken
    {
        $namespacedId = $this->getNamespace().$tokenId;
        $value = $this->generator->generateToken();

        $this->storage->setToken($namespacedId$value);

        return new CsrfToken($tokenId$this->randomize($value));
    }

    

        );
    }

    public function testCsrf()
    {
        $this->csrfTokenManager->expects($this->any())
            ->method('getToken')
            ->willReturn(new CsrfToken('token_id', 'foo&bar'));

        $form = $this->factory->createNamedBuilder('name', 'Symfony\Component\Form\Extension\Core\Type\FormType')
            ->add($this->factory
                // No CSRF protection on nested forms                 ->createNamedBuilder('child', 'Symfony\Component\Form\Extension\Core\Type\FormType')
                ->add($this->factory->createNamedBuilder('grandchild', 'Symfony\Component\Form\Extension\Core\Type\TextType'))
            )
            ->getForm();

        $this->assertWidgetMatchesXpath($form->createView()[],
            '/div [ ./div /following-sibling::input[@type="hidden"][@id="name__token"][@value="foo&bar"] ] [count(.//input[@type="hidden"])=1] '
$passport = $event->getPassport();
        if (!$passport->hasBadge(CsrfTokenBadge::class)) {
            return;
        }

        /** @var CsrfTokenBadge $badge */
        $badge = $passport->getBadge(CsrfTokenBadge::class);
        if ($badge->isResolved()) {
            return;
        }

        $csrfToken = new CsrfToken($badge->getCsrfTokenId()$badge->getCsrfToken());

        if (false === $this->csrfTokenManager->isTokenValid($csrfToken)) {
            throw new InvalidCsrfTokenException('Invalid CSRF token.');
        }

        $badge->markResolved();
    }

    public static function getSubscribedEvents(): array
    {
        return [CheckPassportEvent::class => ['checkPassport', 512]];
    }

            ->createView();

        $this->assertArrayNotHasKey('csrf', $view);
    }

    public function testGenerateCsrfToken()
    {
        $this->tokenManager->expects($this->once())
            ->method('getToken')
            ->with('TOKEN_ID')
            ->willReturn(new CsrfToken('TOKEN_ID', 'token'));

        $view = $this->factory
            ->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [
                'csrf_field_name' => 'csrf',
                'csrf_token_manager' => $this->tokenManager,
                'csrf_token_id' => 'TOKEN_ID',
                'compound' => true,
            ])
            ->createView();

        $this->assertEquals('token', $view['csrf']->vars['value']);
    }

    public function authenticate(RequestEvent $event): void
    {
        $request = $event->getRequest();

        if (null !== $this->csrfTokenManager) {
            $csrfToken = ParameterBagUtils::getRequestParameterValue($request$this->options['csrf_parameter']);

            if (!\is_string($csrfToken) || false === $this->csrfTokenManager->isTokenValid(new CsrfToken($this->options['csrf_token_id']$csrfToken))) {
                throw new LogoutException('Invalid CSRF token.');
            }
        }

        $logoutEvent = new LogoutEvent($request$this->tokenStorage->getToken());
        $this->eventDispatcher->dispatch($logoutEvent);

        if (!$response = $logoutEvent->getResponse()) {
            throw new \RuntimeException('No logout listener set the Response, make sure at least the DefaultLogoutListener is registered.');
        }

        

    public function preSubmit(FormEvent $event)
    {
        $form = $event->getForm();
        $postRequestSizeExceeded = 'POST' === $form->getConfig()->getMethod() && $this->serverParams->hasPostMaxSizeBeenExceeded();

        if ($form->isRoot() && $form->getConfig()->getOption('compound') && !$postRequestSizeExceeded) {
            $data = $event->getData();

            $csrfValue = \is_string($data[$this->fieldName] ?? null) ? $data[$this->fieldName] : null;
            $csrfToken = new CsrfToken($this->tokenId, $csrfValue);

            if (null === $csrfValue || !$this->tokenManager->isTokenValid($csrfToken)) {
                $errorMessage = $this->errorMessage;

                if (null !== $this->translator) {
                    $errorMessage = $this->translator->trans($errorMessage[]$this->translationDomain);
                }

                $form->addError(new FormError($errorMessage$errorMessage[], null, $csrfToken));
            }

            

        );
    }

    public function testCsrf()
    {
        $this->csrfTokenManager->expects($this->any())
            ->method('getToken')
            ->willReturn(new CsrfToken('token_id', 'foo&bar'));

        $form = $this->factory->createNamedBuilder('name', 'Symfony\Component\Form\Extension\Core\Type\FormType')
            ->add($this->factory
                // No CSRF protection on nested forms                 ->createNamedBuilder('child', 'Symfony\Component\Form\Extension\Core\Type\FormType')
                ->add($this->factory->createNamedBuilder('grandchild', 'Symfony\Component\Form\Extension\Core\Type\TextType'))
            )
            ->getForm();

        $this->assertWidgetMatchesXpath($form->createView()[],
            '/table [ ./tr[@style="display: none"] [./td[@colspan="2"]/input [@type="hidden"] [@id="name__token"] ] ] [count(.//input[@type="hidden"])=1] '
$firewallConfig = new FirewallConfig(name: 'my_firewall', userChecker: 'user_checker', logout: ['csrf_parameter' => '_csrf_token', 'csrf_token_id' => 'logout']);
        $firewallMap->expects($this->once())->method('getFirewallConfig')->willReturn($firewallConfig);

        $eventDispatcherLocator = $this->createMock(ContainerInterface::class);
        $eventDispatcherLocator
            ->expects($this->atLeastOnce())
            ->method('get')
            ->willReturnMap([['my_firewall', $eventDispatcher]])
        ;

        $csrfTokenManager = $this->createMock(CsrfTokenManagerInterface::class);
        $csrfTokenManager->expects($this->once())->method('isTokenValid')->with($this->equalTo(new CsrfToken('logout', 'dummytoken')))->willReturn(true);

        $container = $this->createMock(ContainerInterface::class);
        $container->expects($this->once())->method('has')->with('security.csrf.token_manager')->willReturn(true);
        $container
            ->expects($this->atLeastOnce())
            ->method('get')
            ->willReturnMap([
                ['request_stack', $requestStack],
                ['security.token_storage', $tokenStorage],
                ['security.firewall.map', $firewallMap],
                ['security.firewall.event_dispatcher_locator', $eventDispatcherLocator],
                [
$request = $this->container->get('request_stack')->getMainRequest();

        if (!$firewallConfig = $this->container->get('security.firewall.map')->getFirewallConfig($request)) {
            throw new LogicException('Unable to logout as the request is not behind a firewall.');
        }

        if ($validateCsrfToken) {
            if (!$this->container->has('security.csrf.token_manager') || !$logoutConfig = $firewallConfig->getLogout()) {
                throw new LogicException(sprintf('Unable to logout with CSRF token validation. Either make sure that CSRF protection is enabled and "logout" is configured on the "%s" firewall, or bypass CSRF token validation explicitly by passing false to the $validateCsrfToken argument of this method.', $firewallConfig->getName()));
            }
            $csrfToken = ParameterBagUtils::getRequestParameterValue($request$logoutConfig['csrf_parameter']);
            if (!\is_string($csrfToken) || !$this->container->get('security.csrf.token_manager')->isTokenValid(new CsrfToken($logoutConfig['csrf_token_id']$csrfToken))) {
                throw new LogoutException('Invalid CSRF token.');
            }
        }

        $logoutEvent = new LogoutEvent($request$token);
        $this->container->get('security.firewall.event_dispatcher_locator')->get($firewallConfig->getName())->dispatch($logoutEvent);

        $tokenStorage->setToken(null);

        return $logoutEvent->getResponse();
    }

    

        $storage->expects($this->once())
            ->method('hasToken')
            ->with($namespace.'token_id')
            ->willReturn(true);

        $storage->expects($this->once())
            ->method('getToken')
            ->with($namespace.'token_id')
            ->willReturn('TOKEN');

        $this->assertTrue($manager->isTokenValid(new CsrfToken('token_id', 'TOKEN')));
    }

    public function testNonMatchingTokenIsNotValidEmptyNamespace()
    {
        $this->assertNonMatchingTokenIsNotValid(...$this->getEmptyNamespaceMocks());
    }

    public function testNonMatchingTokenIsNotValidHttpsNamespace()
    {
        $this->assertNonMatchingTokenIsNotValid(...$this->getHttpsNamespaceMocks());
    }

    

        $this->csrfTokenManager->expects($this->never())->method('isTokenValid');

        $event = $this->createEvent($this->createPassport(null));
        $this->listener->checkPassport($event);
    }

    public function testValidCsrfToken()
    {
        $this->csrfTokenManager->expects($this->any())
            ->method('isTokenValid')
            ->with(new CsrfToken('authenticator_token_id', 'abc123'))
            ->willReturn(true);

        $event = $this->createEvent($this->createPassport(new CsrfTokenBadge('authenticator_token_id', 'abc123')));
        $this->listener->checkPassport($event);

        $this->expectNotToPerformAssertions();
    }

    public function testInvalidCsrfToken()
    {
        $this->expectException(InvalidCsrfTokenException::class);
        

    protected function isCsrfTokenValid(string $id, #[\SensitiveParameter] ?string $token): bool     {
        if (!$this->container->has('security.csrf.token_manager')) {
            throw new \LogicException('CSRF protection is not enabled in your application. Enable it with the "csrf_protection" key in "config/packages/framework.yaml".');
        }

        return $this->container->get('security.csrf.token_manager')->isTokenValid(new CsrfToken($id$token));
    }

    /** * Adds a Link HTTP header to the current response. * * @see https://tools.ietf.org/html/rfc5988 */
    protected function addLink(Request $request, LinkInterface $link): void
    {
        if (!class_exists(AddLinkHeaderListener::class)) {
            throw new \LogicException('You cannot use the "addLink" method if the WebLink component is not available. Try running "composer require symfony/web-link".');
        }
Home | Imprint | This part of the site doesn't use cookies.