Magento 2 – Allow Only POST Method for Frontend Route

http-requestmagento-2.2.5magento2post-datarouting

I'm using magento 2.2.5 and created a frontend route like this:

<?xml version="1.0"?> 
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="spin" frontName="spin">
            <module name="Neverending_Story" />
        </route>
    </router>
</config>

How can i allow only POST method request that can access this route ??

Best Answer

Magento request object has a function

$this->getRequest()->getMethod() which provide the request method name on request object. So using this getMethod(),you can prevent your route from all other request accept POST..

Create an observer on event

controller_action_predispatch_spin

And on that observer if you will found that the request method $observer->getEvent()->getRequest()->getMethod() ,then dis-allow the all pages of this routes <route id="spin" frontName="spin">

Call observer from 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="controller_action_predispatch_spin">
        <observer instance="StackExchange\Magento\Observer\Frontend\CheckAndPrevent" 
                  name="prevent_all_method"/>
    </event>
</config>

Observer code:

<?php


namespace StackExchange\Magento\Observer\Frontend;


class CheckAndPrevent implements \Magento\Framework\Event\ObserverInterface
{



    public function execute(\Magento\Framework\Event\Observer $observer)
    {
       //$eventParameters = ['controller_action' => $this, 'request' => $request];
        $request = $observer->getEvent()->getRequest();
        $requestMethod = strtolower($request->getMethod());

        if($requestMethod !== 'put'){

           // echo $requestMethod;
            // Throw an exception for prevent the accesss
            throw new \Exception("Cannot access."); 


        }

    }

}