2

I am on Magento 2.3.1 and I am trying to login an admin user automatically given their username. I have tried using the Magento\Backend\Model\Auth\Session class like this:

$this->_authSession->setUser($adminUserName);
$this->_authSession->processLogin();
$this->_authSession->refreshAcl();
$this->_authSession->prolong();

and then redirecting like this:

return $this->_backendUrl->getUrl('admin/dashboard/index');

but it keeps giving me the login prompt instead of the dashboard even though this test:

var_dump($this->_authSession->isLoggedIn());

returns the boolean True.

Any help would be appreciated

2
  • want to login in admin panel programmaticlly?
    – Asad Khan
    May 31, 2019 at 11:35
  • yes, I am trying to automatically log into the admin panel
    – user79886
    May 31, 2019 at 11:40

3 Answers 3

2

This is what i managed to do (based on How to perform auto-login in Magento2 admin?) and is working

?php
require __DIR__ . '/app/bootstrap.php';

class TestApp extends \Magento\Framework\App\Http implements \Magento\Framework\AppInterface {

public function __construct(
    \Magento\Framework\ObjectManagerInterface $objectManager
) {

    $this->_objectManager = $objectManager;
    $this->_eventManager = $this->_objectManager->get('Magento\Framework\Event\Manager');
    $this->_areaList = $this->_objectManager->get('Magento\Framework\App\AreaList');
    $this->_request = $this->_objectManager->get('Magento\Framework\App\Request\Http');
    $this->_response = $this->_objectManager->get('Magento\Framework\App\Response\Http');
    $this->_configLoader = $this->_objectManager->get('Magento\Framework\ObjectManager\ConfigLoaderInterface');
    $this->_state = $this->_objectManager->get('Magento\Framework\App\State');
    $this->_filesystem = $this->_objectManager->get('Magento\Framework\Filesystem');
    $this->registry = $this->_objectManager->get('\Magento\Framework\Registry');

    parent::__construct($objectManager, $this->_eventManager, $this->_areaList, $this->_request, $this->_response, $this->_configLoader, $this->_state, $this->_filesystem, $this->registry);


}

public function launch()
{
    $areaCode = 'adminhtml';
    $username = 'superadmin3';

    $this->_state->setAreaCode($areaCode);

    $this->_request->setPathInfo('/admin');

    $this->_objectManager->configure($this->_configLoader->load($areaCode));

    /** @var \Magento\User\Model\User $user */
    $user = $this->_objectManager->get('Magento\User\Model\User')->loadByUsername($username);

    /** @var \Magento\Backend\Model\Auth\Session $session */
    $session = $this->_objectManager->get('Magento\Backend\Model\Auth\Session');
    $session->setUser($user);
    $session->processLogin();

    if ($session->isLoggedIn()) {
        $cookieManager = $this->_objectManager->get('Magento\Framework\Stdlib\CookieManagerInterface');
        $cookieValue = $session->getSessionId();
        if ($cookieValue) {
            $sessionConfig = $this->_objectManager->get('Magento\Backend\Model\Session\AdminConfig');
            $cookiePath = str_replace('autologin.php', 'index.php', $sessionConfig->getCookiePath());
            $cookieMetadata = $this->_objectManager->get('Magento\Framework\Stdlib\Cookie\CookieMetadataFactory')
                ->createPublicCookieMetadata()
                ->setDuration(3600)
                ->setPath($cookiePath)
                ->setDomain($sessionConfig->getCookieDomain())
                ->setSecure($sessionConfig->getCookieSecure())
                ->setHttpOnly($sessionConfig->getCookieHttpOnly());
            $cookieManager->setPublicCookie($sessionConfig->getName(), $cookieValue, $cookieMetadata);
            /** @var \Magento\Security\Model\AdminSessionsManager $adminSessionManager */
            $adminSessionManager = $this->_objectManager->get('Magento\Security\Model\AdminSessionsManager');
            $adminSessionManager->processLogin();

        }

        /** @var \Magento\Backend\Model\UrlInterface $backendUrl */
        $backendUrl = $this->_objectManager->get('Magento\Backend\Model\UrlInterface');
        $path = $backendUrl->getStartupPageUrl();
        $url = $backendUrl->getUrl($path);
        $url = str_replace('autologin.php', 'index.php', $url);
        header('Location:  '.$url);
        exit;
    }
    return $this->_response;
}
}

$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$app = $bootstrap->createApplication('TestApp');
$bootstrap->run($app);
4
  • 1
    Thanks ! It works ! However, in magento 2.3.1 an instance of the class Magento\Backend\Model\Session\AdminConfig must be used in setPublicCookie to get the correct session name. Otherwise, the cookie is named PHPSESSID and the redirect will prompt the admin panel login page
    – user79886
    May 31, 2019 at 11:59
  • if its works for you then click on the tick mark to help other people as well and also upvote as well. thanks
    – Asad Khan
    May 31, 2019 at 12:02
  • Yeah, just waiting for the edit to get accepted so it works for others as well. Thanks !
    – user79886
    May 31, 2019 at 12:07
  • It doesn't make sense to edit a file in root. Jun 28 at 3:06
0

Try This Code

<?php
/*
 * @author      Mahesh Makwana
 */
namespace VendorName\ModuleName\Controller\Index;

use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Area;

class Index extends \Magento\Framework\App\Action\Action
{
    protected $objectManager;

    protected $request;

    protected $configLoader;

    protected $adminUser;

    protected $authSession;

    protected $cookieManager;

    protected $adminConfig;

    protected $cookieMetadataFactory;

    protected $adminSessionsManager;

    protected $urlInterface;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\ObjectManager\ConfigLoaderInterface $configLoader,
        \Magento\Framework\App\Request\Http $request,
        \Magento\User\Model\UserFactory $adminUser,
        \Magento\Backend\Model\Auth\Session $authSession,
        \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager,
        \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory,
        \Magento\Backend\Model\Session\AdminConfig $adminConfig,
        \Magento\Security\Model\AdminSessionsManager $adminSessionsManager,
        \Magento\Backend\Model\UrlInterface $urlInterface,
        \Magento\Framework\ObjectManagerInterface $objectManager

    ) {
        $this->objectManager = $objectManager;
        $this->request = $request;
        $this->adminUser = $adminUser;
        $this->authSession = $authSession;
        $this->cookieManager = $cookieManager;
        $this->cookieMetadataFactory = $cookieMetadataFactory;
        $this->adminConfig = $adminConfig;
        $this->adminSessionsManager = $adminSessionsManager;
        $this->urlInterface = $urlInterface;
        $this->configLoader = $configLoader;
        parent::__construct($context);
    }

    /**
     * Execute.
     *
     * @return Magento\Framework\Controller\ResultFactory
     */
    public function execute()
    {
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        try {
            $username = 'admin'; // add your admin user name

            $this->request->setPathInfo('/admin');

            $this->objectManager->configure($this->configLoader->load(Area::AREA_ADMINHTML));

            /** @var \Magento\User\Model\User $user */
            $user = $this->adminUser->create()->loadByUsername($username);

            /** @var \Magento\Backend\Model\Auth\Session $session */
            $this->authSession->setUser($user);
            $this->authSession->processLogin();
            if ($this->authSession->isLoggedIn()) {
                $cookieValue = $this->authSession->getSessionId();
                if ($cookieValue) {
                    $cookiePath = $this->adminConfig->getCookiePath();
                    $cookieMetadata = $this->cookieMetadataFactory
                        ->createPublicCookieMetadata()
                        ->setDuration(3600)
                        ->setPath($cookiePath)
                        ->setDomain($this->adminConfig->getCookieDomain())
                        ->setSecure($this->adminConfig->getCookieSecure())
                        ->setHttpOnly($this->adminConfig->getCookieHttpOnly());
                    $this->cookieManager->setPublicCookie($this->adminConfig->getName(), $cookieValue, $cookieMetadata);

                    /** @var \Magento\Security\Model\AdminSessionsManager $adminSessionsManager */
                    $this->adminSessionsManager->processLogin();

                    $resultRedirect->setUrl($this->urlInterface->getUrl('admin/dashboard/index'));
                    return $resultRedirect;
                } else{
                    $this->messageManager->addError(__('invalid cookie value.'));
                }
            } else {
                $this->messageManager->addError(__('invalid admin user.'));
            }
        } catch (\Exception $e) {
            $this->messageManager->addError(__('Something went wrong while login to admin.'));
        }

        $resultRedirect->setUrl($this->_redirect->getRefererUrl());
        return $resultRedirect;
    }
}
-1

Admin login programmatically using root script

https://www.integerbyteblog.in/magento/admin-login-programmatically-in-magento-2/

Your Answer

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

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