Generating URL with CSRF token 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' =&gt; TRUE])-&gt;toString()


It generates a route with a token:

http://example.com/mp/ajax/authorized?token=91018d3f93299fe116c5596ea32d9addca063a92


I also tried the url_generator service to generate the URL:

$url_generator = \Drupal::service('url_generator');
$url = $url_generator-&gt;generateFromRoute('mp.ajax.authorized', [], ['absolute' =&gt; 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:

1qG-Tw4AyQgNmVWtlkp_to7mielSz8ZfQZAkhWqAlsQ


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' =&gt; TRUE, 'query' =&gt; ['token' =&gt; \Drupal::csrfToken()-&gt;get()]])-&gt;toString()


However, this token fails validation in Drupal\Core\Access\CsrfAccessCheck, so it appears this is not the correct solution.
Well, I found a solution, however, I'd be amazed if there isn't a better way to do it, and in fact I'm pretty sure it's bypassing the placeholder API, so it's likely the wrong way to do it. But until someone gives me a better solution, it's a working one.

The solution is to generate the token manually, then set it as a GET query on the URL when generating the URL. 

When generating the token however, you need the internal path for the route, which is used as a basis for generating the token.

$url = Url::fromRoute('mp.ajax.authorized');
$token = \Drupal::csrfToken()-&gt;get($url-&gt;getInternalPath());
$url-&gt;setOptions(['absolute' =&gt; TRUE, 'query' =&gt; ['token' =&gt; $token]]);
$absolute_url = $url-&gt;toString()


Note that I've already found this method doesn't work on routes with optional parameters, so if someone comes across this, you'll have to find another method in such a case.