Sharing Authentication Between Socket.io and a PHP Frontend (Using JSON Web Tokens)

DZone 's Guide to

Sharing Authentication Between Socket.io and a PHP Frontend (Using JSON Web Tokens)

Learn the steps and code to create an authentication link between Socket.io and a PHP frontend using JSON Web Tokens.

· Web Dev Zone ·
Free Resource

I’ve written a previous post about sharing authentication between Socket.io and a PHP frontend, but after publishing it, a colleague (hi @mariotux) told me that I can use JSON Web Tokens (JWT) to do this. I had never used JWT before, so I decided to study them a little bit.

JWT are pretty straightforward. You only need to create the token and send it to the client—you don’t need to store it within a database. The client can decode and validate it on its own. You also can use any programming language to encode and decode tokens (JWT are available in the most common ones).

We’re going to create the same example in the previous post. Today, with JWT, we don’t need to pass the PHP session and perform a HTTP request to validate it. We’ll only pass the token. Our Node.js server will validate by its own.

var io = require('socket.io')(3000),
 jwt = require('jsonwebtoken'),
 secret = "my_super_secret_key";

// middleware to perform authorization
io.use(function (socket, next) {
 var token = socket.handshake.query.token,
 try {
 decodedToken = jwt.verify(token, secret);
 console.log("token valid for user", decodedToken.user);
 socket.connectedUser = decodedToken.user;
 } catch (err) {
 next(new Error("not valid token"));

io.on('connection', function (socket) {
 console.log('Connected! User: ', socket.connectedUser);

That’s the client:

<!DOCTYPE html>
<html lang="en">
 <meta charset="UTF-8">
Welcome {{ user }}!

<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script src="/assets/jquery/dist/jquery.js"></script>

 var socket;
 $(function () {
 $.getJSON("/getIoConnectionToken", function (jwt) {
 socket = io('http://localhost:3000', {
 query: 'token=' + jwt

 socket.on('connect', function () {

 socket.on('error', function (err) {


And here's the backend. A simple Silex server very similar to the one in my previous post. JWT also has several reserved claims. For example “exp” to set up an expiration timestamp. It’s very useful. We set only one value, and the validator will reject tokens with incorrect timestamps. In this example, I’m not using an expiration date. That means that my token will never expire. And never means never.

In my first prototype, I set up a small expiration date (10 seconds). That means my token is only available for 10 seconds. Sounds great. My backend generates tokens that are going to be used immediately. That’s the normal situation but, what happens if I restart the socket.io server? The client will try to reconnect using the token, but it has expired. We’ll need to create a new JWT before reconnecting. Because of that, I’ve removed expiration date in this example but remember: Without expiration dates, your generated tokens will be always valid (and always is a very long time).

include __DIR__ . "/../vendor/autoload.php";

use Firebase\JWT\JWT;
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([
 'secret' => "my_super_secret_key",
 'debug' => true
$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 (Application $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('/getIoConnectionToken', function (Application $app) {
 $user = $app['session']->get('user');
 if (null === $user) {
 throw new AccessDeniedHttpException('Access Denied');

 $jwt = JWT::encode([
 // I can use "exp" reserved claim. It's cool. My connection token is only available
 // during a period of time. The problem is if I restart the io server. Client will
 // try to re-connect using this token and it's expired.
 //"exp" => (new \DateTimeImmutable())->modify('+10 second')->getTimestamp(),
 "user" => $user
 ], $app['secret']);

 return $app->json($jwt);

$app->get('/private', function (Application $app) {
 $user = $app['session']->get('user');

 if (null === $user) {
 throw new AccessDeniedHttpException('Access Denied');

 $userName = $user['username'];

 return $app['twig']->render('private.twig', [
 'user' => $userName

For the full project, here's my GitHub.

Related Refcard:

frontend, json, jwt, php, silex, tokens

Published at DZone with permission of Gonzalo Ayuso , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}