If you want to remove ‘Invalid security or form key. Please refresh the page’ error message when logged in to Magento admin 2.4.x, then you need to make changes to the following file.
Step 1 : Open the vendor file like /vendor/magento/module-backend/App/Action/Plugin/Authentication.php and override to your custom theme
Step 2 : Find below code in the bottom section of the Authentication.php file. Approx line no. 228
$requestParts = explode('/', trim($request->getRequestUri(), '/'), 3);
$baseUrlPath = trim(parse_url($this->backendUrl->getBaseUrl(), PHP_URL_PATH), '/');
$routeIndex = empty($baseUrlPath) ? 0 : 1;
$requestUri = $this->_url->getUrl($requestParts[$routeIndex]);
Step 3 : Replace above code with below mentioned code
$requestParts = strpos(trim($request->getRequestUri(),'/'), $request->getFrontName()) === 0 ?
explode('/', trim($request->getRequestUri(), '/'), 4) :
explode('/', trim($request->getRequestUri(), '/'), 3);
if (($key = array_search($request->getFrontName(), $requestParts)) !== false) {
unset($requestParts[$key]);
}
$requestParams = $request->getParams();
unset($requestParams['key'], $requestParams['form_key']);
$requestUri = $this->_url->getUrl(implode('/', $requestParts), $requestParams);
Step 4 : After change above code, please run below mentioned commands
- php bin/magento setup:upgrade - php bin/magento setup:static-content:deploy - php bin/magento cache:clean
That’s it…
Now logout your admin panel and again logged in and see your error now resolved…

