title: ZF2 authentication session storage in memcached
body: <p>In our intranet application(s) we use SSO (single sign on) login while the sessions both on client and auth origin applications are stored in memcached.</p>
  
  <p>The sessions are set to live for 12h before the garbage collector may consider them as for removal. Both applications are written using ZF2.</p>
  
  <p>Unfortunately, the problem is, that after certain period of time (I don't have the exact value) the browser loses the session which causes the redirection to auth origin, where the session is still alive thus user is redirected back to client and the browser session is refreshed. This is not a big deal if the user has no unsaved work as these two redirects happen within 1 second and user even may not notice them.</p>
  
  <p>But it really is a big deal when user has unsaved work and even an attempt to save it leads to redirects and the work is gone.</p>
  
  <p>Here is the configuration of session in <code>Bootstrap.php</code>:</p>
  
  <pre class="lang-php prettyprint-override"><code>class Module
  {
      public function onBootstrap(MvcEvent $e)
      {
          // ...
          $serviceManager      = $e-&gt;getApplication()-&gt;getServiceManager();
          $sessionManager      = $serviceManager-&gt;get('session_manager_memcached');
          $sessionManager-&gt;start();
          Container::setDefaultManager($sessionManager);
          // ...
      }
  
      public function getServiceConfig()
      {
          return array(
              'factories' =&gt; array(
                  // ...
                  'session_manager_memcached' =&gt; function ($sm) {
                      $systemConfig = $sm-&gt;get('config');
                      $config = new SessionConfig;
                      $config-&gt;setOptions(array(
                          'phpSaveHandler' =&gt; 'memcache',
                          'savePath' =&gt; 'tcp://localhost:11211?timeout=1&amp;amp;retry_interval=15&amp;amp;persistent=1',
                          'cookie_httponly' =&gt; true,
                          'use_only_cookies' =&gt; true,
                          'cookie_lifetime' =&gt; 0,
                          'gc_maxlifetime' =&gt; 43200, // 12h
                          'remember_me_seconds' =&gt; 43200 // 12h
                      ));
                      return new SessionManager($config);
                  },
                  // ...
          );
      }
  }
  </code></pre>
  
  <p>The authentication service is defined as</p>
  
  <pre><code>            'authService' =&gt; function ($sm) {
                  $authService = new \Zend\Authentication\AuthenticationService;
                  $authService-&gt;setStorage(new \Zend\Authentication\Storage\Session('user_login'));
                  return $authService;
              },
  </code></pre>
  
  <ul>
  <li>the session storage uses the same memcached session manager.</li>
  </ul>
  
  <p>Then anywhere within the application a session value needs to be retrieved or set I just use a <code>\Zend\Session\Container</code> like this:</p>
  
  <pre class="lang-php prettyprint-override"><code>$sessionContainer = new \Zend\Session\Container('ClientXYZ');
  $sessionContainer['key1'] = $val1;
  // or
  $val2 = $sessionContainer['key2'];
  </code></pre>
  
  <p>The SSO is requested for the active session at any action using the <em>token</em> from session which contains PHPSESSID from the auth origin. It's quite complicated to describe here within this question.</p>
  
  <p>Additionally an authentication service stores a user identity (with roles for ACL) also in memcached session - using the same settings. Obviously this is now the place which causes confusion. Apparently the session storage of authentication service times out prematurely causing the ACL to retrieve no user identity to check leading into SSO logout sequence (but because user didn't really log out, SSO redirects the user back as described above).</p>
  
  <p>I'm not sure how much code should I (and can I) share here, maybe you'll lead me to the solution straight away or just by asking me some questions. I am quite helpless right now after many hours of debugging and trying to identify the problem.</p>
  
  <p>Somewhere I have read that memcached wipes out the memory once the session <em>cookie</em> gets 1MB in size - may this be the case? For the user identity we save just general user information and array of roles, I'd guess this could be max. up to few kb in size...</p>
  
  <p><strong>EDIT 1:</strong> To dismiss all guesses and to save your time, here few facts (to keep an eye on):</p>
  
  <ul>
  <li>only memcached is used</li>
  <li>cookies serve only to transport the <code>PHPSESSID</code> between the browser and server and it's value is the key for memory chunk in memcached where the data is stored</li>
  <li>client and SSO auth apps are running on one server (be it integration, staging or live environment, still just one server)</li>
  <li>session on client app goes off randomly causing it to redirect to SSO auth app, but here the session is still alive thus user is redirected back to client app which gets new session and user stays logged in</li>
  <li>this should dismiss discussion about memcached being wiped off or restarted</li>
  <li>also observation on telneted memcached directly shows both data chunks (for client and auth apps) are established almost at the same time with the same ttl</li>
  </ul>
  
  <p>I am going to implement some <code>die</code>s in PHP and <code>return</code>s in JS parts to catch the moment when the session is considered gone and further inspect the browser cookie, memcached data, etc. and will update you (unless somebody comes with explanation and solution).</p>