diff --git a/core/modules/toolbar/src/Controller/ToolbarController.php b/core/modules/toolbar/src/Controller/ToolbarController.php
index 8d25465ffd083ced9e2e8230e717a373e34e682d..f15de6241dac42af001ad5dd7756ce552bf75f7c 100644
--- a/core/modules/toolbar/src/Controller/ToolbarController.php
+++ b/core/modules/toolbar/src/Controller/ToolbarController.php
@@ -31,13 +31,19 @@ public function __construct(
   /**
    * Returns an AJAX response to render the toolbar subtrees.
    *
+   * @param string $hash
+   *   The hash of the toolbar subtrees to validate.
+   *
    * @return \Drupal\Core\Ajax\AjaxResponse
    *   The AJAX response containing the rendered toolbar subtrees.
    */
-  public function subtreesAjax() {
+  public function subtreesAjax(string $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
@@ -64,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 51986310901c36d68581647545e351e7e05abdaa..b8619002306f7d811a8e8a7ddde7077801a96713 100644
--- a/core/modules/toolbar/toolbar.module
+++ b/core/modules/toolbar/toolbar.module
@@ -165,6 +165,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];
 }