I have a route that requires a CSRF token:
mp.ajax.authorized: path: /mp/ajax/authorized defaults: _controller: 'Drupal\mp\Controller\AjaxController::authorizedCallback' requirements: _csrf_token: 'TRUE'
I need to generate a URL for this route. As the route has _csrf_token set to TRUE, the route needs to contain a CSRF token.
I've generated a URL from the route using Url:
Url::fromRoute('mp.ajax.authorized', , ['absolute' => TRUE])->toString()
It generates a route with a token:
I also tried the url_generator service to generate the URL:
$url_generator = \Drupal::service('url_generator'); $url = $url_generator->generateFromRoute('mp.ajax.authorized', , ['absolute' => TRUE]);
And it generates the same URL.
However, the token on the URL is incorrect, as the actual CSRF token that is retrieved from CsrfTokenGenerator is:
I've done some reading, and it appears that the token given from Url is a placeholder, but I need the actual token, not the placeholder. Does anyone know how to get this?
Update: I've discovered I can retrieve the URL with a token in it by passing token as a parameter to the Url builder:
Url::fromRoute('mp.ajax.authorized', , ['absolute' => TRUE, 'query' => ['token' => \Drupal::csrfToken()->get()]])->toString()
However, this token fails validation in Drupal\Core\Access\CsrfAccessCheck, so it appears this is not the correct solution.