Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Magento 2.1.1 login to backend programatically, from frontend:
<?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
class TestApp extends \Magento\Framework\App\Http implements \Magento\Framework\AppInterface {
public function launch() {
$areaCode = 'adminhtml';
$username = 'reseller';
$this->_request->setPathInfo('/admin_ves');
$this->_state->setAreaCode($areaCode);
$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($session->getName(), $cookieValue, $cookieMetadata);
$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 = Bootstrap::create(BP, $_SERVER);
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap->createApplication('TestApp');
$bootstrap->run($app);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.