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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • What Is API-First?
  • Using PHP Headers When Serving JSON Data
  • Using OKTA as Client Provider in Mulesoft
  • Securing Spring Boot Microservices with JSON Web Tokens (JWT)

Trending

  • Accelerating Debugging in Integration Testing: An Efficient Search-Based Workflow for Impact Localization
  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples
  • Automating Data Pipelines: Generating PySpark and SQL Jobs With LLMs in Cloudera
  • Detection and Mitigation of Lateral Movement in Cloud Networks
  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.0K 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.

Related

  • What Is API-First?
  • Using PHP Headers When Serving JSON Data
  • Using OKTA as Client Provider in Mulesoft
  • Securing Spring Boot Microservices with JSON Web Tokens (JWT)

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!