Sharing authentication between socket.io and a PHP frontend

Sharing authentication between socket.io and a PHP frontend

Normally, when I work with websockets, my stack is a socket.io server and a Silex frontend. Protect a PHP frontend with one kind of authentication of another is pretty straightforward. But if we want to use websockets, we need to set up another server and if we protect our frontend we need to protect our websocket server too.

If our frontend is node too (express for example), sharing authentication is more easy but at this time we we want to use two different servers (a node server and a PHP server). I’ve written about it too but today we`ll see another solution. Let’s start.

Imagine we have this simple Silex application. It has three routes:

  • “/” a public route
  • “/login” to perform the login action
  • “/private” a private route. If we try to get here without a valid session we’ll get a 403 error

And this is the code. It’s basically one example using sessions taken from Silex documentation:

use Silex\Application; use Silex\Provider\SessionServiceProvider; use Silex\Provider\TwigServiceProvider; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; $app = new Application(); $app->register(new SessionServiceProvider()); $app->register(new TwigServiceProvider(), [ 'twig.path' => __DIR__ . '/../views', ]); $app->get('/', function (Application $app) { return $app['twig']->render('home.twig'); }); $app->get('/login', function () use ($app) { $username = $app['request']->server->get('PHP_AUTH_USER', false); $password = $app['request']->server->get('PHP_AUTH_PW'); if ('gonzalo' === $username && 'password' === $password) { $app['session']->set('user', ['username' => $username]); return $app->redirect('/private'); } $response = new Response(); $response->headers->set('WWW-Authenticate', sprintf('Basic realm="%s"', 'site_login')); $response->setStatusCode(401, 'Please sign in.'); return $response; }); $app->get('/private', function () use ($app) { $user = $app['session']->get('user'); if (null === $user) { throw new AccessDeniedHttpException('Access Denied'); } return $app['twig']->render('private.twig', [ 'username' => $user['username'] ]); }); $app->run();

Our “/private” route also creates a connection with our websocket server:


Originally published at www.laravelfeed.com.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.