I have an application where I created a REST resource to update a field on the user object to store bookmarked items.
When you do a post request to a rest resource you are required to use a header with X-CSRF-Token.
You can get this by making a call to "/session/token". But I'm wondering if it's OK, if you have a "bookmarks" widget on all pages to include the token in drupal settings.
Or is this some kind of security issue?
Is it better to make a call through javascript to get the token, rather than have it in the drupal settings?
Or as long as you're logged in, having the csrf token in drupal settings is not a problem?
/**
* Implements hook_preprocess_HOOK().
*/
function mymodule_preprocess_page(&$vars) {
// Add CSRF token to page for authenticated users. Token
// is required by rest resources on POST requests.
if ($vars['logged_in']) {
$route = \Drupal::routeMatch()->getRouteObject();
$is_admin = \Drupal::service('router.admin_context')->isAdminRoute($route);
if (!$is_admin) {
$vars['#attached']['drupalSettings']['user']['csrf'] = \Drupal::csrfToken()->get(CsrfRequestHeaderAccessCheck::TOKEN_KEY);
}
}
}