2

I need to provide a list of CSRF tokens in drupalSettings for every anonymous user to make safe requests to API endpoints. The CSRF service mentions the need for session to exist for the seed, but I do not know how to correctly create the session.

This is what I tried in a hook_page_attachments_alter() implementation.

/**
 * Implements hook_page_attachments_alter().
 */
function foo_page_attachments_alter(array &$attachments) {
  // Needed for persistent, per-user, csrf tokens.
  $session = \Drupal::request()->getSession();
  if ($session->isStarted() === FALSE) {
    $session->start();
  }

  /** @var Drupal\Core\Access\CsrfTokenGenerator $csrf */
  $csrf = \Drupal::service('csrf_token');

  $attachments['#attached']['drupalSettings']['foo']['tokens'] = [
    'pathA' => $csrf->get('/pathA'),
    'pathB' => $csrf->get('/pathB')
  ];

  $session->save();
}

I have also tried the following way to verify the session has been started, but none of them worked.

if (session_status() === PHP_SESSION_NONE) {
  session_start();
}
\Drupal::service('session_manager')->start();
\Drupal::service('session_manager')->save();
\Drupal::service('session_manager')->regenerate();
\Drupal::service('session')->start();
\Drupal::service('session')->migrate();

The complete code I am using is the following one.

1

1 Answer 1

0

As suggested by the @4uk4's comment posted for the question, the solution is saving a value into the session.

/**
 * Implements hook_page_attachments_alter().
 */
function foo_page_attachments_alter(array &$attachments) {
  // Needed for persistent, per-user, csrf tokens.
  $session = \Drupal::service('session');
  /** @var Drupal\Core\Access\CsrfTokenGenerator $csrf */
  $csrf = \Drupal::service('csrf_token');

  if (!$session->isStarted()) {
    $session->start();
    $session->set('foo', 'bar');
  }

  $attachments['#attached']['drupalSettings']['foo']['tokens'] = [
    'pathA' => $csrf->get('/pathA'),
    'pathB' => $csrf->get('/pathB')
  ];
}

There is also no need to call $session->save().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.