title: PHP Websocket authenticate user in a test (pass session cookie)
body: <p>I am trying to test a scenario, that on the one hand, anonymous users should immediately get a disconnect from a Websocket connection and on the other hand, authenticated users should stay in the websocket connection. The first case is easy testable by using the code down under. The authentication process is not working.</p>
  
  <p>For session storage, I am using Cookie authentication in combination with a database: <a href="http://symfony.com/doc/current/cookbook/doctrine/pdo_session_storage.html" rel="noreferrer">Symfony PDO Session Storage</a>. It's all working fine, but when it comes to testing the described behaviour by using authentication, I don't know how to authenticate the user in a test. As a client, I am using <a href="https://github.com/ratchetphp/Pawl" rel="noreferrer">Pawl asynchronous Websocket client.</a> This looks the following:</p>
  
  <pre><code>\Ratchet\Client\connect('ws://127.0.0.1:8080')-&gt;then(function($conn) {
      $conn-&gt;on('message', function($msg) use ($conn) {
          echo "Received: {$msg}\n";
      });
  
      $conn-&gt;send('Hello World!');
  }, function ($e) {
      echo "Could not connect: {$e-&gt;getMessage()}\n";
  });
  </code></pre>
  
  <p>I know that as a third parameter, I can pass header information to the "connect" method, but I cannot find a way so that the client is connected and the cookie is passed correctly during the ws handshake. I thought of something like:</p>
  
  <ol>
  <li>Authenticate a client by creating an <a href="http://symfony.com/doc/current/cookbook/testing/simulating_authentication.html" rel="noreferrer">authentication token</a></li>
  <li>I create a new entry in the session table in database with serialized user</li>
  <li>I pass the created cookie as a third argument to the connect method</li>
  </ol>
  
  <p>This is the theory I thought that would work, but the user always stays anonym on websocket side. Here the code to the theory so far:</p>
  
  <pre><code>// ...
  use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
  
  class WebsocketTest extends WebTestCase
  {
  
      static $closed;
  
      protected function setUp()
      {
        self::$closed = null;
      }
  
  
      public function testWebsocketConnection()
      {
        $loop = Factory::create();
        $connector = new Connector($loop);
  
        // This user exists in database user tbl
        $symfClient = $this-&gt;createSession("testuser@test.com");
  
        $connector('ws://127.0.0.1:80', [], ['Origin' =&gt; 'http://127.0.0.1', 'Cookie' =&gt; 
                   $symfClient-&gt;getContainer()-&gt;get('session')-&gt;getName() . '=' 
                  . $symfClient-&gt;getContainer()-&gt;get('session')-&gt;getId()])
          -&gt;then(function(WebSocket $conn) use($loop){
  
              $conn-&gt;on('close', function($code = null, $reason = null) use($loop) {
                  self::$closed = true;
                  $loop-&gt;stop();
              });
              self::$closed = false;
  
          }, function(\Exception $e) use ($loop) {
              $this-&gt;fail("Websocket connection failed");
              $loop-&gt;stop();
          });
  
        $loop-&gt;run();
  
        // Check, that user stayed logged
        $this-&gt;assertFalse(self::$closed);
      }
  
      private function createSession($email)
      {
        $client = static::createClient();
        $container = $client-&gt;getContainer();
  
        $session = $container-&gt;get('session');
        $session-&gt;set('logged', true);
  
        $userManager = $container-&gt;get('fos_user.user_manager');
        $em = $container-&gt;get('doctrine.orm.entity_manager');
        $loginManager = $container-&gt;get('fos_user.security.login_manager');
        $firewallName = 'main';
  
        $user = $userManager-&gt;findUserByEmail($email);
  
        $loginManager-&gt;loginUser($firewallName, $user);
  
        // save the login token into the session and put it in a cookie
        $container-&gt;get('session')-&gt;set('_security_' . $firewallName,
          serialize($container-&gt;get('security.token_storage')-&gt;getToken()));
        $container-&gt;get('session')-&gt;save();
        $client-&gt;getCookieJar()-&gt;set(new Cookie($session-&gt;getName(), $session-&gt;getId()));
  
  
        // Create session in database
        $pdo = new PDOSessionStorage();
        $pdo-&gt;setSessId($session-&gt;getId());
        $pdo-&gt;setSessTime(time());
        $pdo-&gt;setSessData(serialize($container-&gt;get('security.token_storage')-&gt;getToken()));
        $pdo-&gt;setSessLifetime(1440);
  
        $em-&gt;persist($pdo);
        $em-&gt;flush();
  
        return $client;
    }
  
  }
  </code></pre>
  
  <p>As config_test.yml, I configured the session the following way:</p>
  
  <pre><code>session:
      storage_id:     session.storage.mock_file
      handler_id:     session.handler.pdo
  </code></pre>
  
  <p>For server side websocket implementation, I am using Ratchet, which is being wrapped by the following Symfony bundle: <a href="https://github.com/GeniusesOfSymfony/WebSocketBundle" rel="noreferrer">Gos Websocket Bundle</a></p>
  
  <p>How to authenticate the user when testing websockets? On websocket server, the user is always something like "anon-15468850625756b3b424c94871115670", but when I test manually, he gets connected correct.</p>
  
  <p>Additional question (secondary): How to test the subscription to topics? (pubsub)
  There are no blog entries or anything else about this on the internet.</p>
  
  <p>Update: No one ever functional tested their websockets? Is this unimportant, useless or why can't anyone help on that important topic?</p>