npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@espaker/socketio-jwt-auth

v1.0.1

Published

Socket.io authentication middleware using Json Web Token

Downloads

7

Readme

SocketIO JWT Auth

Travis Coveralls github npm GitHub license

Socket.io authentication middleware using Json Web Token

Work with socket.io >= 1.0

Installation

npm install socketio-jwt-auth

Usage

Register the middleware with socket.io

socketio-jwt-auth has only one method authenticate(options, verify).

options is an object literal that contains options:

  • secret a secret key,
  • algorithm, defaults to HS256, and
  • succeedWithoutToken, which, if true tells the middleware not to fail if no token is suppled. Defaults tofalse.

verify is a function with two args payload, and done:

  • payload is the decoded JWT payload, and
  • done is an error-first callback with three args: done(err, user, message)
var io = require('socket.io')();
var jwtAuth = require('socketio-jwt-auth');

// using middleware
io.use(jwtAuth.authenticate({
  secret: 'Your Secret',    // required, used to verify the token's signature
  algorithm: 'HS256'        // optional, default to be HS256
}, function(payload, done) {
  // done is a callback, you can use it as follows
  User.findOne({id: payload.sub}, function(err, user) {
    if (err) {
      // return error
      return done(err);
    }
    if (!user) {
      // return fail with an error message
      return done(null, false, 'user does not exist');
    }
    // return success with a user info
    return done(null, user);
  });
}));

Connecting without a token

There are times when you might wish to successfully connect the socket but indentify the connection as being un-authenticated. For example when a user connects as a guest, before supplying login credentials. In this case you must supply the option succeedWithoutToken, as follows:

var io = require('socket.io')();
var jwtAuth = require('socketio-jwt-auth');

// using middleware
io.use(jwtAuth.authenticate({
  secret: 'Your Secret',    // required, used to verify the token's signature
  algorithm: 'HS256',        // optional, default to be HS256
  succeedWithoutToken: true
}, function(payload, done) {
  // you done callback will not include any payload data now
  // if no token was supplied
  if (payload && payload.sub) {
    User.findOne({id: payload.sub}, function(err, user) {
      if (err) {
        // return error
        return done(err);
      }
      if (!user) {
        // return fail with an error message
        return done(null, false, 'user does not exist');
      }
      // return success with a user info
      return done(null, user);
    });
  } else {
    return done() // in your connection handler user.logged_in will be false
  }
}));

Access user info

io.on('connection', function(socket) {
  console.log('Authentication passed!');
  // now you can access user info through socket.request.user
  // socket.request.user.logged_in will be set to true if the user was authenticated
  socket.emit('success', {
    message: 'success logged in!',
    user: socket.request.user
  });
});

io.listen(9000);

Client Side

<script>
  // You should add auth_token to the query when connecting
  // Replace THE_JWT_TOKEN with the valid one
  var socket = io('http://localhost:9000', {query: 'auth_token=THE_JWT_TOKEN'});
  // For socket.io v3 you must use 'auth' object in place of 'query'
  // var socket = io('http://localhost:9000', {auth: 'auth_token=THE_JWT_TOKEN'});
  // Connection failed
  socket.on('error', function(err) {
    throw new Error(err);
  });
  // Connection succeeded
  socket.on('success', function(data) {
    console.log(data.message);
    console.log('user info: ' + data.user);
    console.log('logged in: ' + data.user.logged_in)
  })
</script>

If your client support, you can also choose to pass the auth token in headers.

<script>
  // Use extraHeaders to set a custom header, the key is 'x-auth-token'.
  // Don't forget to replace THE_JWT_TOKEN with the valid one.
  var socket = io('http://localhost:9000', {
    extraHeaders: {
      'x-auth-token': 'THE_JWT_TOKEN'
    },
    transportOptions: {
      polling: {
        extraHeaders: {
          'x-auth-token': 'THE_JWT_TOKEN'
        }
      }
    },
  });
  // ...
</script>

Tests

npm install
npm test

Change Log

0.2.1

  • Fix a bug caused by undefined

0.2.0

  • Add auth handshake for Socket.IO v3

0.1.0

  • Add support for passing auth token with extraHeaders

0.0.6

  • Fix an api bug of node-simple-jwt

0.0.5

  • Add an option (succeedWithoutToken) to allow guest connection

License

The MIT License

Copyright (c) 2015 Lei Lei