trait SynchronizeCsrfTokenSeedTrait

Same name and namespace in other branches
  1. 10 core/modules/ckeditor5/tests/src/Traits/SynchronizeCsrfTokenSeedTrait.php \Drupal\Tests\ckeditor5\Traits\SynchronizeCsrfTokenSeedTrait
  2. 11.x core/modules/ckeditor5/tests/src/Traits/SynchronizeCsrfTokenSeedTrait.php \Drupal\Tests\ckeditor5\Traits\SynchronizeCsrfTokenSeedTrait

Synchronizes the child site's CSRF token seed back to the test runner.

For the test to be able to generate valid CSRF tokens, it needs access to the CSRF token seed in the child site (i.e. tested site). This requires reading the CSRF token seed from the session that gets created in the child site after logging in, and then setting it in the test runner's container. Otherwise, the test runner would generate its own CSRF token seed and would hence generate CSRF tokens that are not valid for the session in the child site.

@internal

Hierarchy

See also

\Drupal\Core\Access\CsrfTokenGenerator::get()

2 files declare their use of SynchronizeCsrfTokenSeedTrait
ImageUploadTest.php in core/modules/ckeditor5/tests/src/Functional/ImageUploadTest.php
MediaEntityMetadataApiTest.php in core/modules/ckeditor5/tests/src/Functional/MediaEntityMetadataApiTest.php

File

core/modules/ckeditor5/tests/src/Traits/SynchronizeCsrfTokenSeedTrait.php, line 22

Namespace

Drupal\Tests\ckeditor5\Traits
View source
trait SynchronizeCsrfTokenSeedTrait {
    
    /**
     * {@inheritdoc}
     */
    protected function drupalLogin(AccountInterface $account) {
        parent::drupalLogin($account);
        $session_data = $this->container
            ->get('session_handler.write_safe')
            ->read($this->getSession()
            ->getCookie($this->getSessionName()));
        $csrf_token_seed = unserialize(explode('_sf2_meta|', $session_data)[1])['s'];
        $this->container
            ->get('session_manager.metadata_bag')
            ->setCsrfTokenSeed($csrf_token_seed);
    }
    
    /**
     * {@inheritdoc}
     */
    protected function rebuildContainer() {
        parent::rebuildContainer();
        // Ensure that the CSRF token seed is reset on container rebuild.
        if ($this->loggedInUser) {
            $current_user = $this->loggedInUser;
            $this->drupalLogout();
            $this->drupalLogin($current_user);
        }
    }
    
    /**
     * {@inheritdoc}
     */
    protected function drupalLogout() {
        parent::drupalLogout();
        $this->container
            ->get('session_manager.metadata_bag')
            ->stampNew();
    }

}

Members


Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.