diff --git a/core/modules/toolbar/src/Controller/ToolbarController.php b/core/modules/toolbar/src/Controller/ToolbarController.php
index bcb36f8382b8a91669ead01284620bb3eb4547c3..bd3f9d7b11ffe253c68fc3c508ec6e5b09e8127a 100644
--- a/core/modules/toolbar/src/Controller/ToolbarController.php
+++ b/core/modules/toolbar/src/Controller/ToolbarController.php
@@ -37,10 +37,13 @@ public function __construct(
    *
    * @return \Drupal\Core\Ajax\AjaxResponse
    */
-  public function subtreesAjax() {
+  public function subtreesAjax($hash) {
     [$subtrees] = toolbar_get_rendered_subtrees();
+    $expected_hash = _toolbar_get_subtrees_hash()[0];
     $response = new AjaxResponse();
-    $response->addCommand(new SetSubtreesCommand($subtrees));
+    if (hash_equals($expected_hash, $hash)) {
+      $response->addCommand(new SetSubtreesCommand($subtrees));
+    }
 
     // The Expires HTTP header is the heart of the client-side HTTP caching. The
     // additional server-side page cache only takes effect when the client
@@ -67,8 +70,7 @@ public function subtreesAjax() {
    *   The access result.
    */
   public function checkSubTreeAccess($hash) {
-    $expected_hash = _toolbar_get_subtrees_hash()[0];
-    return AccessResult::allowedIf($this->currentUser()->hasPermission('access toolbar') && hash_equals($expected_hash, $hash))->cachePerPermissions();
+    return AccessResult::allowedIf($this->currentUser()->hasPermission('access toolbar'))->cachePerPermissions();
   }
 
   /**
diff --git a/core/modules/toolbar/toolbar.module b/core/modules/toolbar/toolbar.module
index ff395da0fcfc8c3e1c6e589bad9f7f3aee489c62..915c36d03e68027493b7cde5ba469496d184c9ee 100644
--- a/core/modules/toolbar/toolbar.module
+++ b/core/modules/toolbar/toolbar.module
@@ -293,6 +293,6 @@ function toolbar_get_rendered_subtrees() {
  */
 function _toolbar_get_subtrees_hash() {
   [$subtrees, $cacheability] = toolbar_get_rendered_subtrees();
-  $hash = Crypt::hashBase64(serialize($subtrees));
+  $hash = Crypt::hashBase64(serialize(array_keys($subtrees)));
   return [$hash, $cacheability];
 }