DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • What Is API-First?
  • Using PHP Headers When Serving JSON Data
  • Using OKTA as Client Provider in Mulesoft
  • Building Threat Intelligence Pipelines Using Python, APIs, and Elasticsearch

Trending

  • Testing AI-Infused Apps: A Dual-Layer Framework for AI Quality Assurance
  • How to Build an Agentic AI SRE Co-Pilot for Incident Response
  • Building a High-Throughput Distributed Sequence Generator Using the Hi-Lo Algorithm
  • Why Your AI Agent's Logs Aren't Earning Trust
  1. DZone
  2. Coding
  3. Languages
  4. Sharing Authentication Between Socket.io and a PHP Frontend (Using JSON Web Tokens)

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.

By 
Gonzalo Ayuso user avatar
Gonzalo Ayuso
·
Jun. 08, 16 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
10.2K Views

Join the DZone community and get the full member experience.

Join For Free

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,
 decodedToken;
 try {
 decodedToken = jwt.verify(token, secret);
 console.log("token valid for user", decodedToken.user);
 socket.connectedUser = decodedToken.user;
 next();
 } catch (err) {
 console.log(err);
 next(new Error("not valid token"));
 //socket.disconnect();
 }
});

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

That’s the client:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
</head>
<body>
Welcome {{ user }}!

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

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

 socket.on('connect', function () {
 console.log("connected!");
 });

 socket.on('error', function (err) {
 console.log(err);
 });
 });
 });
</script>

</body>
</html>


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).

<?php
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
 ]);
});
$app->run();

For the full project, here's my GitHub.

Related Refcard:

Core JSON

JSON PHP Socket.IO authentication

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

Opinions expressed by DZone contributors are their own.

Related

  • What Is API-First?
  • Using PHP Headers When Serving JSON Data
  • Using OKTA as Client Provider in Mulesoft
  • Building Threat Intelligence Pipelines Using Python, APIs, and Elasticsearch

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook