0

here is the code:

events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="backend_auth_user_login_success">
        <observer name="my_custom_login_success_observer" instance="Example\CatIntegration\Observer\AdminLoginSucceeded" />
    </event>
</config>

AdminLoginSucceeded.php

<?php

namespace Example\CatIntegration\Observer;

use Magento\Framework\Event\ObserverInterface;

class AdminLoginSucceeded implements ObserverInterface
{

    private $resultRedirectFactory;
    protected $_storeManager;
    protected $responseFactory;
    private $url;
    protected $adminSession;

    public function __construct(
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Magento\Framework\Controller\Result\RedirectFactory $resultRedirectFactory,
        \Magento\Framework\UrlInterface $url,
        \Magento\Backend\Model\Auth\Session $adminSession
    ){
        $this->_storeManager = $storeManager;
        $this->url = $url;
        $this->responseFactory = $responseFactory;
        $this->resultRedirectFactory = $responseFactory;
        $this->adminSession = $adminSession;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $event = $observer->getEvent();
        $roleData = $this->adminSession->getUser()->getRole()->getData();

        //if (strpos($roleData['role_name'], 'test') !== false) {

            $RedirectUrl= $this->url->getUrl('example/customcat/index');
            $this->responseFactory->create()->setRedirect($RedirectUrl)->sendResponse();

            /*$writer = new \Zend_Log_Writer_Stream(BP . '/var/log/AdminLoginSucceeded.log');
            $logger = new \Zend_Log();
            $logger->addWriter($writer);
            $logger->info($roleData['role_name']);*/

            die();
 
        //}


    }

}

the above code works in http, but when i put it in https production env, it show me

Invalid security or form key. Please refresh the page.

1 Answer 1

1

The issue you are facing could be due to Magento's built-in security measures that check for form keys to prevent CSRF attacks. You can try adding the form key to the URL to fix this issue.

Here's how you can modify your code to add the form key to the URL:

    use Magento\Framework\App\ActionFlag;
    use Magento\Framework\App\CsrfAwareActionInterface;
    use Magento\Framework\App\Request\InvalidRequestException;
    use Magento\Framework\App\RequestInterface;
    use Magento\Framework\App\Request\csrfValidator;

    class AdminLoginSucceeded implements ObserverInterface, CsrfAwareActionInterface
    {
        /**
         * @var RequestInterface
         */
        private $request;
        /**
         * @var ActionFlag
         */
        private $actionFlag;
        /**
         * @var CsrfValidator
         */
        private $csrfValidator;

        public function __construct(
            RequestInterface $request,
            ActionFlag $actionFlag,
            CsrfValidator $csrfValidator,
            \Magento\Framework\Controller\Result\RedirectFactory $resultRedirectFactory,
            \Magento\Framework\UrlInterface $url,
            \Magento\Backend\Model\Auth\Session $adminSession
        ) {
            $this->request = $request;
            $this->actionFlag = $actionFlag;
            $this->csrfValidator = $csrfValidator;
            $this->resultRedirectFactory = $resultRedirectFactory;
            $this->url = $url;
            $this->adminSession = $adminSession;
        }

        public function execute(\Magento\Framework\Event\Observer $observer)
        {
            $event = $observer->getEvent();
            $roleData = $this->adminSession->getUser()->getRole()->getData();

            //if (strpos($roleData['role_name'], 'test') !== false) {

            $RedirectUrl = $this->url->getUrl('example/customcat/index', ['_secure' => true, 'form_key' => $this->formKey->getFormKey()]);
            $this->responseFactory->create()->setRedirect($RedirectUrl)->sendResponse();

            /*$writer = new \Zend_Log_Writer_Stream(BP . '/var/log/AdminLoginSucceeded.log');
            $logger = new \Zend_Log();
            $logger->addWriter($writer);
            $logger->info($roleData['role_name']);*/

            die();

            //}
        }

        public function createCsrfValidationException(
            RequestInterface $request
        ): ?InvalidRequestException {
            return null;
        }

        public function validateForCsrf(RequestInterface $request): ?bool
        {
            return $this->csrfValidator->validate($request);
        }
    }

This code adds the form key to the URL by passing the _secure and form_key parameters to the getUrl() method. The _secure parameter ensures that the URL is generated with the correct protocol (HTTPS in this case), and the form_key parameter ensures that the form key is included in the URL.

Note that you also need to implement the CsrfAwareActionInterface interface and its methods (createCsrfValidationException() and validateForCsrf()) to ensure that the form key validation works properly.

5
  • PHP Fatal error: Declaration of Example\CatIntegration\Observer\AdminLoginSucceeded::execute(Magento\Framework\Event\Observer $observer) must be compatible with Magento\Framework\App\ActionInterface::execute() in /var/html/example/app/code/Example/CatIntegration/Observer/AdminLoginSucceeded.php on line 62 if i remove CsrfAwareActionInterface, the result is the same
    – hkguile
    Commented Mar 9, 2023 at 6:07
  • Which magento version you are using ? Commented Mar 9, 2023 at 6:26
  • magento 2.4.3-p2
    – hkguile
    Commented Mar 9, 2023 at 6:32
  • i just tried to implements CsrfAwareActionInterface in target controller, it works for me, but seems not a good practice
    – hkguile
    Commented Mar 9, 2023 at 6:36
  • Yes but this is the patch, I already applied this for a client because client don't want to upgrade magento version due to budget... in the upgraded version it has been fixed. If you are satisfied my answer please upvote. It is up to you. Commented Mar 9, 2023 at 6:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.