Our Work

Magento2 Admin/Customer Login Issues with Cookies/Sessions

Updated today

In this article are focusing on how magento cookies can create issue with the login functionality of both Customer Frontend and Admin backend, the reason why it occurs and how it should be resolved. This is also known as looping issue, as the screen redirects itself to the same screen even though username and password is correct. Also a script is provided at the end of the article which can help detect few of the issues. Feel free to use and modify as per your needs.

What is Cookie?
A cookie is a piece of text that a Web server can store on a user's browser (hard disk) and also later can retrieve it. Magento uses cookies in Cart & Backend Adminhtml functionalities, and they may be source for few problems not able to login Magento Frontend or Backend.

What is Session?
A session is array variable at the server side, which stores information to be used across multiple pages. For example Added Items to the Cart are typically saved in sessions and when the user browses the checkout page they are read from the session. Sessions are identified by an unique ID whose name changes based on the programming languages, in PHP its called ‘PHP Session ID’ . As you might have guessed the same PHP Session ID needs to be stored as cookie in the client browser to relate.

Magento storage of Sessions

Magento can store sessions via multiple session providers and this can be configured in the Magento Config file app/etc/local.xml. These session providers can be chosen here.

  • File
<session_save>
<![CDATA[files]]>
</session_save>
<session_save_path>
<![CDATA[/tmp/session]]>
</session_save_path>
  • Database

Enabling sessions storing to DB is done in /app/etc/local.xml by adding

Magento application stores session in Core_session table.

  • Redis
<session_save>db</session_save>
<redis_session>
<host>127.0.0.1</host>
<port>6379</port>
</redis_session>
  • MemCache
session_save>
<![CDATA[memcache]]>undefined</session_save>undefined<session_save_path>
<![CDATA[tcp://localhost:11211?persistent=1&weight=2&timeout=10&retry_interval=10]]>undefined</session_save_path>

Magento Usage
Magento uses two different cookies named ‘frontend’ and ‘adminhtml’, first one is created when any page is browsed and the same cookie is also updated when customer logins, the next one is created when backend user(Admin) is logged in. You can check if the cookies are created by clicking Inspect Element -> Application as in the below picture(from Chrome)

Cookies are configured in magento via configuration Admin menu, select ‘System -> Configuration -> General -> Web’

Problem - Login doesn’t work and it redirects again to login page

If you haven’t experienced this problem then you haven't worked that long in Magento . This is how it typically happens, when you login by entering username and password you will be redirected to the same login page and url, and your browser is appended with nonce id. This happens for both Customer FrontEnd and Magento Backend login.

Let's look few reasons why this happens and how we should resolve those issues.

Reason #1: Cookie domain does not match server domain

Let’s say your magento site is example.com and cookie domain in Magento ‘System -> Configuration -> General -> Web’ configured as xyz.com.

In this scenario both magento cookie (frontend and adminhtml) will create with ‘Domain Value’ as xyz.com but for validating the session magento will consider the domain through which the site was accessed i.e. example.com, since it won't be able to find active session with domain value example.com , it will redirect to login page even when valid credentials are provided.

app/code/core/Mage/Core/Model/Session/Abstract.php

//After login or logout Magento system will regenerate the session using following script

<?php
public
function init($namespace, $sessionName = null)
        {
        if (!isset($_SESSION))
                {
                $this->start($sessionName);
                }
        if (!isset($_SESSION[$namespace]))
                {
                $_SESSION[$namespace] = array();
                }
        $this->_data = & $_SESSION[$namespace];
        $this->validate();
        $this->revalidateCookie();
        return $this;
        }

app/code/core/Mage/Core/Model/Session/Abstract/Varien.php

// Magento will validate the session for every request in following method

<?php
public
function init($namespace, $sessionName = null)
        {
        if (!isset($_SESSION))
                {
                $this->start($sessionName);
                }
        if (!isset($_SESSION[$namespace]))
                {
                $_SESSION[$namespace] = array();
                }
        $this->_data = & $_SESSION[$namespace];
        $this->validate();
        $this->revalidateCookie();
        return $this;
        }

You may normally see this when you migrate your magento instance from one domain to another domain, for example from Production to Staging and forgot changing the cookie domain.

Note: you can run cookieTest.php provided script which validates what is the server cookie domain and what is set magento config for ‘cookie domain’.

Solution:

Change the Cookie Domain via configuration Admin menu, select ‘System -> Configuration -> General -> Web’ as per the screenshot Alternatively change this by running these sql queries.

For validating the cookie domain use following select query to get the configuration SELECT * FROM core_config_data WHERE path = 'web/cookie/cookie_domain';
After executing the above query we will get the results. Verify the ‘value’ column is same as your domain or not. Please update the value if it is not same as your domain.

For Updating the cookie domain use following query :

UPDATE core_config_data SET VALUE="domain.com" WHERE path='web/cookie/cookie_domain';

Reason #2: Multiple Subdomains used and your cookie magento Configuration is not done correctly

Let's say your site is example.com. Logging into example.com/admin works fine there. But on a your staging/ QA site for example staging.example.com/admin, you are not able to login without deleting all cookies. System may allows to login to staging.example.com but when we are logging again to example.com/admin your next click on the staging.example.com kicks back to the login page. Similar behaviour is experienced for customer frontend login also.

Solution 1 :

Option A: If your main domain and subdomains are hosted on same server
  • Change the Cookie Domain via configuration Admin menu, select ‘System -> Configuration -> General -> Web’ as per the screenshot
  • See if Cookie Domain is example.com, or .example.com( a dot in front). If not set it to .example.com . even example.com is fine.
Option B: If your main domain and subdomains hosted on different servers
  • Change the Cookie Domain via configuration Admin menu, select ‘System -> Configuration -> General -> Web’ as per the screenshot
  • See if Cookie Domain is www.example.com, or .www.example.com( a dot in front). If not set it to .www.example.com . even www.example.com is fine.
  • In the test.example.com shop, set the following, set the Cookie domain to .test.example.com on the test-environment

Alternatively change this by running these sql queries.

For validating the cookie domain use following select query to get the configuration
SELECT * FROM core_config_data WHERE path = 'web/cookie/cookie_domain';
After executing the above query we will get the results. Verify the ‘value’ column is same as your domain or not. Please update the value if it is not same as your domain.
For Updating the cookie domain use following query :
UPDATE core_config_data SET VALUE = "domain.com" WHERE path = 'web/cookie/cookie_domain';

Solution 2:

  • Check if your php.ini has the same cookie domain as in your Magento Config ‘System -> Configuration -> General -> Web’ if not change it to the same as Magento config as below
    • session.cookie_domain = example.com

Solution 3:

This is not recommended approach, but if all options fail are you can try this code changing option by changing adminhtml cookie name for subdomains. Copy this file action.php and keep it the same folder path as local so your core code file can be overridden. Two changes in file app/code/core/Mage/Core/Controller/Varien/Action.php.

  • In function preDispatch change lines
/** @var $session Mage_Core_Model_Session */ $session = Mage::getSingleton('core/session', array('name' => $this->_sessionNamespace))->start();
to
$namespace = $this->_sessionNamespace.($_SERVER['SERVER_NAME']=='subdomain.example.com'?'_subdomain':''); /** @var $session Mage_Core_Model_Session */ $session = Mage::getSingleton('core/session', array('name' => $namespace))->start();
  • In function setRedirectWithCookieCheck change
/** @var $session Mage_Core_Model_Session */ session = Mage::getSingleton('core/session', array('name' => $this->_sessionNamespace));
to
$namespace = $this->_sessionNamespace.($_SERVER['SERVER_NAME']=='subdomain.example.com'?'_subdomain':''); /** @var $session Mage_Core_Model_Session */ $session = Mage::getSingleton('core/session', array('name' => $namespace));
  • And after that search for text

Mage::getSingleton('core/session', array('name' => 'adminhtml'));

in all files and replace it with

Mage::getSingleton('core/session',array('name'=>'adminhtml'.($_SERVER['SERVER_NAME']=='subdomain.example.com'?'_subdomain':'')));

if any occurrences would be found.

Reason #3 Double frontend cookies causing intermittent login issues

In few scenarios there are possibilities of system creating multiple frontend cookies and because of which system won't allow you to login.

Scenario 1: When your magento system has same configuration for main domain and subdomain in the magento config System -> Configuration -> General -> Web’ and if the users logins to both the sites magento system creates two cookies one with ‘Domain Value’ with main domain and another with subdomain, as such we will have two frontend cookie sessions so we won't be able to login to the system

Solution

Change ‘Cookie Domain’ in ‘System -> Configuration -> General -> Web’ to .example.com for both domain and subdomain configurations.

Solution 1:

Add cookie domain to  your php.ini file same as your magento config.
session.cookie_domain = example.com

Solution 2:

Change ‘Cookie Domain’  in  ‘System -> Configuration -> General -> Web’ to .example.com for both domain and subdomain configurations.

Note: Using our cookieTest.php script see if you have double frontend cookies.

Reason #4 Failed to create(read) session ID

Recoverable Error: session_regenerate_id(): Failed to create(read) session ID: user (path: /var/lib/php/sessions) in app/code/core/Mage/Core/Model/Session/Abstract/Varien.php on line 492
This error you may see in the exception log, and might occur only for PHP7 issue as PHP7 does strict type checking. The solution for this is however to change in the magento core read function by typecasting. More on this https://github.com/Inchoo/Inchoo_PHP7/issues/4

public function read($sessId) {
//return $data;
return (string)$data;
}

Reason #5 Warning: session_start(): Session data file is not created by your uid

Warning: session_start(): Session data file is not created by your uid in app/code/core/Mage/Core/Model/Session/Abstract/Varien.php on line 125

Solution 1:

This error occurs if you are saving session on files, and the folder or files lack webserver user permission. So in case of nginx if your webserver user is www-data, you need to grant ownership to the folder using

Solution 2:

If you are running on vagrant you may have to  make sure or change the file session path

Solution 3:

Also another reason could be there are some old sessions in the var/sessions folder delete them and try it.

Note:
If you have option to use different session providers, switch to another for example REDIS to FILE clear you var/cache folder and see if it works and again try this only in your development environment.

Php Script to detect Cookie Issues

<?php
ini_set('display_errors', 1);
$mageFileName = getcwd() . '/app/Mage.php';
require $mageFileName;
Mage::app();
echo "<b> Server Cookie Domain Configuration : </b> " . ini_get('session.cookie_domain') . "<br>";
foreach (Mage::app()->getStores() as $store) {
    echo "<b>" . $store->getName() . "</b><br>";
    $configCookieDomain = Mage::getStoreConfig('web/cookie/cookie_domain', $store->getId());
    $storeConfigUrl     = Mage::getStoreConfig('web/unsecure/base_url', $store->getId());
    $sourceUrl          = parse_url($storeConfigUrl);
    $storeDomain        = $sourceUrl['host'];
    $cookieDomainResult = ($configCookieDomain == $storeDomain || $configCookieDomain == '.' . $storeDomain) ? "" : "not";
    echo "Config cookie Domain : " . $configCookieDomain . " and Store Domain: " . $storeDomain . " " . $cookieDomainResult . " configured properly<br>";
}
//echo "<b>Request Cookies:</b> ";
$requestCookie    = Mage::app()->getRequest()->getHeader('cookie');
$requestCookieArr = explode(';', $requestCookie);
$sessionIds       = array();
foreach ($requestCookieArr as $requestCookieItem) {
    $cookieValue = explode('=', $requestCookieItem);
    // echo $requestCookieItem."<br>";
    if (trim($cookieValue[0]) == 'frontend' || trim($cookieValue[0]) == 'adminhtml') {
        $cookieName                = trim($cookieValue[0]);
        $sessionId                 = trim($cookieValue[1]);
        $sessionIds[$cookieName][] = $sessionId;
    }
}
$areas = array(
    "frontend",
    "adminhtml"
);
foreach ($areas as $area => $cookieName) {
    echo "<b>validating " . $cookieName . " cookie </b><br>";
    $cookieExpires  = Mage::getModel('core/cookie')->getLifetime($cookieName);
    $cookiePath     = Mage::getModel('core/cookie')->getPath($cookieName);
    $cookieDomain   = Mage::getModel('core/cookie')->getDomain($cookieName);
    $cookieSecure   = Mage::getModel('core/cookie')->isSecure($cookieName);
    $cookieHttpOnly = Mage::getModel('core/cookie')->getHttponly($cookieName);
    echo "Cookie Lifetime : " . $cookieExpires . " <br>";
    echo "Cookie Path : " . $cookiePath . " <br>";
    echo "Cookie Domain : " . $cookieDomain . " <br>";
    echo "Cookie Is Secure : " . $cookieSecure . " <br>";
    echo "Cookie Httponly : " . $cookieHttpOnly . " <br>";
    if (count($sessionIds[$cookieName]) > 1) {
        echo "<span style='color:red'><b>We have " . count($sessionIds[$cookieName]) . " " . $cookieName . " Cookies with values : </b>" . implode(',', $sessionIds[$cookieName]) . "<br>";
        //$encryptedSessionId = Mage::getSingleton("core/session")->getEncryptedSessionId();
        $encryptedSessionId = Mage::getModel('core/cookie')->get($cookieName);
        echo "Original Cookie value : " . $encryptedSessionId . "<br>";
        echo "Please verify the Subdomain and Main Site Cookie Domain Configuration</span><br>";
    }
}
?>

Output:

Magento Store EN
Config cookie Domain : staging.abc.com and Store Domain: staging.abc.com configured properly
Magento Store FR
Config cookie Domain : staging.abc.com and Store Domain: staging.abc.com configured properly
validating frontend cookie
Cookie Lifetime : 31536000
Cookie Path : /
Cookie Domain : staging.zeb.be
Cookie Is Secure :
Cookie Httponly : 1
validating adminhtml cookie
Cookie Lifetime : 31536000
Cookie Path : /
Cookie Domain : staging.zeb.be
Cookie Is Secure :
Cookie Httponly : 1

Looking for Magento Developer?

Please Contact us if you have any Magento Implementation requirements. Hire dedicated Magento developers or Magento Development services from KTree. KTree is Best offshore Magento E-commerce development company with extensive experience in E-commerce development and Magento Plugins.

Request For Quote