Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Security] CSRF token validation failure in functional tests #50209

Closed
@mmarchois

Description

@mmarchois

Symfony version(s) affected

6.2.8

Description

Since the upgrade to version 6.2.8, the validation of csrf tokens in our functional tests does not work anymore. All my tests throw the exception "Invalid CSRF token".

How to reproduce

The controller i want to test :

// ...
public function __invoke(Request $request): Response
{
        // ...
        $csrfToken = new CsrfToken('token-name', $request->request->get('token'));
        if (!$this->csrfTokenManager->isTokenValid($csrfToken)) {
            throw new BadRequestHttpException('Invalid CSRF token');
        }
}

The functional test :

// ...
use SessionHelper;

public function testDelete(): void
{
    $client = $this->loginUser($user) ;
    $client->request('DELETE', 'my-url', [
        'token' => $this->generateCsrfToken($client, 'token-name'),
    ]) ;
}

Token generation on the test side :

trait SessionHelper
{
    public function getSession(KernelBrowser $client) : Session
    {
        $cookie = $client->getCookieJar()->get('MOCKSESSID') ;

        // create a new session object
        $container = static::getContainer() ;
        $sessionSavePath = $container->getParameter('session.save_path') ;
        $sessionStorage = new MockFileSessionStorage($sessionSavePath) ;
        $session = new Session($sessionStorage) ;
        $session->setId($cookie->getValue()) ;
        $session->start() ;

        return $session ;
    }

    public function generateCsrfToken(KernelBrowser $client, string $tokenId) : string
    {
        $session = $this->getSession($client) ;
        $container = static::getContainer() ;
        $tokenGenerator = $container->get('security.csrf.token_generator') ;
        $csrfToken = $tokenGenerator->generateToken() ;
        $session->set(SessionTokenStorage::SESSION_NAMESPACE . "/{$tokenId}", $csrfToken) ;
        $session->save() ;

        return $csrfToken ;
    }
}

Note that this code worked in 6.2.7.

Possible Solution

No response

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions