Drupal - Generating URL with CSRF token
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()->get($url->getInternalPath());
$url->setOptions(['absolute' => TRUE, 'query' => ['token' => $token]]);
$absolute_url = $url->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.
Based on the code of Jaypan but with additional parameter (node id):
routing.yml:
entity.node.publish:
path: '/node/{node}/toggleStatus'
defaults:
_controller: 'Drupal\publishcontent\Controller\PublishContentPublishEntity::toggleEntityStatus'
requirements:
_csrf_token: 'TRUE'
_publish_access_check: 'TRUE'
custom function:
$nid = 100;
$url = Url::fromRoute('entity.node.publish', ['node' => $nid]);
$token = \Drupal::csrfToken()->get($url->getInternalPath());
$url->setOptions(['absolute' => TRUE, 'query' => ['token' => $token]]);
$absolute_url = $url->toString();
Will return something like this:
https://www.exapmle.com/node/100/toggleStatus?token=PF06yJ7PLR052_HxeTWvsuye88d7NAZgwanN3yiswU