CSRF requires calling stampNew on the session metadata. There's also a trick for rendering CSRF protected routes due to Drupal core leveraging placeholders for delayed rendering.
/**
* Get the string URL for a CSRF protected route.
*
* @param \Drupal\Core\Url $url
* The URL.
*
* @return string
* The URL string.
*/
protected function getCsrfUrlString(Url $url): string {
$context = new RenderContext();
$url = $this->container->get('renderer')->executeInRenderContext($context, function () use ($url) {
return $url->toString();
});
$bubbleable_metadata = $context->pop();
assert($bubbleable_metadata instanceof BubbleableMetadata);
$build = [
'#plain_text' => $url,
];
$bubbleable_metadata->applyTo($build);
return (string) $this->container->get('renderer')->renderPlain($build);
}
/**
* Creates a user, its session, and sets it as the current user.
*
* @return \Drupal\user\UserInterface
* The user.
*/
protected function createUserWithSession(): UserInterface {
$this->container->get('session_manager.metadata_bag')->stampNew();
$user = $this->createUser(['administer site configuration']);
self::assertNotFalse($user);
$this->container->get('current_user')->setAccount($user);
return $user;
}
CSRF requires calling
stampNew
on the session metadata. There's also a trick for rendering CSRF protected routes due to Drupal core leveraging placeholders for delayed rendering.