I need to provide list of CSRF tokens in drupalSettings for every anonymous user so JS can make safe requests to api endpoints.
The CSRF service mentions the need for session to exist for the seed but I am not clear about how to create the session correctly. I tried various approaches but none seem to work correctly.
So far I have tried:
if (session_status() === PHP_SESSION_NONE) { session_start(); } // or Drupal::service('session_manager')->start(); // or Drupal::service('session_manager')->save(); // or Drupal::service('session_manager')->regenerate(); // or Drupal::service('session')->start(); // or Drupal::service('session')->migrate();
I am trying this in my route controller hook_page_attachments_alter.
This is my code:
/** * 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(); } // or Drupal::service('session_manager')->start(); /** @var DrupalCoreAccessCsrfTokenGenerator $csrf */ $csrf = Drupal::service('csrf_token'); $attachments['#attached']['drupalSettings']['foo']['tokens'] = [ 'pathA' => $csrf->get('/pathA'), 'pathB' => $csrf->get('/pathB') ]; $session->save(); // or Drupal::service('session_manager')->save(); }
Sponsored by SupremePR