Magento 2 issue : Invalid security or form key. Please refresh the page.


Invalid security or form key. Please refresh the page.
magento2 - Custom Module Controller: Invalid security or form key. Please  refresh the page - Magento Stack Exchange

This is a new bug when using another URL than admin.

You need to make changes to the following file:

\vendor\magento\module-backend\App\Action\Plugin\Authentication.php

See the code changes over at https://github.com/magento/magento2/issues/33749#issuecomment-908145941

This issue will be resolved in 2.4.4.

Change the \vendor\magento\module-backend\App\Action\Plugin\Authentication.php 

Change the function _redirectIfNeededAfterLogin in this file. replace with the following code:

    protected function _redirectIfNeededAfterLogin(\Magento\Framework\App\RequestInterface $request)
    {
        $requestUri = null;

        // Checks, whether secret key is required for admin access or request uri is explicitly set
        if ($this->_url->useSecretKey()) {
            // $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]);
            $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);
        } elseif ($request) {
            $requestUri = $request->getRequestUri();
        }

        if (!$requestUri) {
            return false;
        }

        $this->_response->setRedirect($requestUri);
        $this->_actionFlag->set('', \Magento\Framework\App\ActionInterface::FLAG_NO_DISPATCH, true);
        return true;
    }




Did you find this article useful?