Authentication in realtime frameworks can be challenging. Perhaps this is because the way these systems work is quite different from a regular web app. The risk of not correctly authenticating your sockets traffic is that you could end up sniffing information on other users streams. The socket server will not automagically know about the logged-in user, thus anyone could join any stream.

This first diagram shows this common misconception:

It is a common misconception that a user who is authenticated in the hosting web appliction, is also authenticated in the socket stream. These are two completely different channels.

Cookie-based and Token-based Auth

There are two ways of solving this problem: the traditional cookie-based approach or a token-based approach. The following diagram explains how each of these methods work:

In our previous article, we wrote about the benefits of a token-based architecture: Cookies vs Tokens. Getting auth right with Angular.JS. Here are some specific considerations with cookies and realtime frameworks:

  • Coupling: the first issue when using cookies is that you have to couple the web application authentication mechanism with the socket server authentication. This might be ok in some cases, but it means you are tied to the semantics of the authentication framework which was written with a specific web use case in mind. e.g.: the session cookie is handled by the web framework and you don't have access to that easily unless you know the internals.
  • Hard to configure: The configuration is error prone. A year ago I wrote passport-socketio that basically bridges the passport information stored in the express session with auth. Looking at the issues, most of the problems are related to the configuration or people being unfamiliar with passport.js.
  • Not ready for devices: If you are connecting to a socket from a device, cookies are not there (well, they are but you have to get into cookie containers and what not), so you end up implementing something different for a device.
  • Requires session configuration: you have to rely on a session store (e.g. Mongodb, Redis, or store the session on a cookie).
  • PHP + Socket.IO: Reading the PHP cookie and session from node is not easy, here is a blogpost explaining it. Same thing applies to other technologies (django, java, etc.).

Authenticating Sockets using Tokens

By now you should not be surprised if we proposed a different alternative to cookies: using tokens. Let's look at a simple sample that uses express, and handles authentication using Json Web Tokens (JWT).

Server Side

Code speaks by itself. Focus on the /login and the usage of socketioJwt.authorize.

var jwt = require('jsonwebtoken');
// other requires'/login', function (req, res) {

  // TODO: validate the actual user user
  var profile = {
    first_name: 'John',
    last_name: 'Doe',
    email: '',
    id: 123

  // we are sending the profile in the token
  var token = jwt.sign(profile, jwtSecret, { expiresInMinutes: 60*5 });

  res.json({token: token});

var server = http.createServer(app);

Then the server

var socketioJwt = require('socketio-jwt');

var sio = socketIo.listen(server);

sio.set('authorization', socketioJwt.authorize({
  secret: jwtSecret,
  handshake: true

  .on('connection', function (socket) {
     console.log(, 'connected');

server.listen(9000, function () {
  console.log('listening on http://localhost:9000');

The JWT is signed with the jwtSecret which is stored only on the server.

Here we are using the global authorization callback on We are also using a simple module wrote (socketio-jwt) to help us with the details of handling the JWT. This module expects the JWT in the querystring during the handshake.

If the client sends a valid JWT, the handshake completes successfully and the connection event is triggered.

Client Side

A simple js client side code that uses this server is shown bellow:

function connect_socket (token) {
  var socket = io.connect('', {
    query: 'token=' + token

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

$('#login').submit(function (e) {
  $.post('/login', {
    username: $('username').val(),
    password: $('password').val()
  }).done(function (result) {

As stated before, this is much simpler than using cookies and sessions, and it is much easier to implement across different technologies.

The complete sample is available for download here.

You could use a very similar approach with WebSockets, this is an example with einaros/ws.

Aside: Auth0 Authentication with JavaScript

At Auth0, we make heavy use of full-stack JavaScript to help our customers to manage user identities including password resets, creating and provisioning, blocking and deleting users. We also created a serverless platform, called Auth0 Extend, that enables customers to run arbitrary JavaScript functions securely. Therefore, it must come as no surprise that using our identity management platform on JavaScript web apps is a piece of cake.

Auth0 offers a free tier to get started with modern authentication. Check it out, or sign up for a free Auth0 account here!

Auth0 Login Page

It's as easy as installing the auth0-js and jwt-decode node modules like so:

npm install jwt-decode auth0-js --save

Then implement the following in your JS app:

const auth0 = new auth0.WebAuth({
  clientID: "YOUR-AUTH0-CLIENT-ID", // E.g.,
  domain: "YOUR-AUTH0-DOMAIN",
  scope: "openid email profile YOUR-ADDITIONAL-SCOPES",
  audience: "YOUR-API-AUDIENCES", // See
  responseType: "token id_token",
  redirectUri: "http://localhost:9000" //YOUR-REDIRECT-URL

function logout() {
  window.location.href = "/";

function showProfileInfo(profile) {
  var btnLogin = document.getElementById('btn-login');
  var btnLogout = document.getElementById('btn-logout');
  var avatar = document.getElementById('avatar');
  document.getElementById('nickname').textContent = profile.nickname; = "none";
  avatar.src = profile.picture; = "block"; = "block";

function retrieveProfile() {
  var idToken = localStorage.getItem('id_token');
  if (idToken) {
    try {
      const profile = jwt_decode(idToken);
    } catch (err) {
      alert('There was an error getting the profile: ' + err.message);

auth0.parseHash(window.location.hash, (err, result) => {
  if (err || !result) {
     // Handle error

  // You can use the ID token to get user information in the frontend.
  localStorage.setItem('id_token', result.idToken);
  // You can use this token to interact with server-side APIs.
  localStorage.setItem('access_token', result.accessToken);

function afterLoad() {
  // buttons
  var btnLogin = document.getElementById('btn-login');
  var btnLogout = document.getElementById('btn-logout');

  btnLogin.addEventListener('click', function() {

  btnLogout.addEventListener('click', function() {


window.addEventListener('load', afterLoad);

Get the full example using this code.

Go ahead and check out our Quick Start tutorials to learn how to implement authentication using different languages and frameworks in your apps.