Magento 2 Admin – 401 Controller Error Solution

adminhtmlajaxmagento2module

I currently have a module that adds a field to the admin cms page. I've written a controller and on input change I want to ajax this controller.

This is the simple controller I added to start testing:

namespace Vendor\Module\Controller\Adminhtml\Index;

use Magento\Framework\Controller\ResultFactory;

class Index extends \Magento\Framework\App\Action\Action
{
    /**
     * Save action
     *
     * @return void
     */
    public function execute()
    {
        die('Hello world');
    }  

}

My Router is located in:

Vendor\Module\etc\adminhtml\routes.xml

And looks like the following:

<router id="admin">
        <route frontName="namehere" id="namehere">
            <module name="Vendor_Module" before="Magento_Backend" />
        </route>
    </router>

I've added the following into a block to call in the admin cms page:

public function getFormAction()
    {
        return '/admin/namehere/index/index';
    }

And when I call this controller via the block in the ajax request or even access the controller I get either redirected to the dashboard with an error of key issue or via the ajax:

Status Code: 401 Unauthorized

or

Invalid security or form key. Please refresh the page.

Now I'm logged in as the admin so shouldn't have any permission issues. Why am I getting a 401? I'm pretty stumped. Any help always appreciated.

Best Answer

For adminarea you should use \Magento\Backend\App\Action instead of \Magento\Framework\App\Action\Action

class Index extends \Magento\Backend\App\Action
Related Topic