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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  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.

Gonzalo Ayuso user avatar by
Gonzalo Ayuso
·
Jun. 08, 16 · Tutorial
Like (1)
Save
Tweet
Share
9.35K 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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Container Security: Don't Let Your Guard Down
  • Microservices Testing
  • Tracking Software Architecture Decisions
  • How We Solved an OOM Issue in TiDB with GOMEMLIMIT

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: