All Projects → adcentury → socketio-jwt-auth

adcentury / socketio-jwt-auth

Licence: MIT license
Socket.io authentication middleware using Json Web Token

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to socketio-jwt-auth

ExpressJS-SocketIO-Boilerplate
📦 Simple Express.js & Socket.io Boilerplate
Stars: ✭ 31 (-64.37%)
Mutual labels:  socket-io, auth
rust cms
使用Rust编写一个CMS(内容管理系统)可以做为个人博客,公司网站
Stars: ✭ 32 (-63.22%)
Mutual labels:  auth
php-jwt
Convenience library for working with JSON Web Tokens (JWT) in PHP
Stars: ✭ 34 (-60.92%)
Mutual labels:  json-web-token
blog-single-user-websocket
Enforcing a single web socket connection per user with Node.js, Socket.IO, and Redis. Sample repository for my article on Medium.
Stars: ✭ 67 (-22.99%)
Mutual labels:  socket-io
socketio-demos
Socket.io Getting Started
Stars: ✭ 44 (-49.43%)
Mutual labels:  socket-io
quickmeet
A video chat/meeting webapp using WebRTC and WebSockets. Basically a Google Meet clone + a collaborative Whiteboard.
Stars: ✭ 75 (-13.79%)
Mutual labels:  socket-io
rocket auth
An implementation for an authentication API for Rocket applications.
Stars: ✭ 65 (-25.29%)
Mutual labels:  auth
Project12-C-Slack-Web
🔥🔥🔥🚀⚡ [12-C팀] 겁나 빠른 슬랙 프로젝트 ⚡🚀🔥🔥🔥
Stars: ✭ 22 (-74.71%)
Mutual labels:  socket-io
SocketIOSharp
C# implementation of Socket.IO protocol revision 4 client and server.
Stars: ✭ 101 (+16.09%)
Mutual labels:  socket-io
vuejwtauth
Client-side JWT auth package for Vue.js (and Quasar) applications
Stars: ✭ 13 (-85.06%)
Mutual labels:  auth
rust-socketio
An implementation of a socket.io client written in the Rust programming language.
Stars: ✭ 198 (+127.59%)
Mutual labels:  socket-io
insight auth
身份验证服务
Stars: ✭ 32 (-63.22%)
Mutual labels:  auth
spiced academy--p2p chat
A fun and easy messaging app that allows private conversations through P2P
Stars: ✭ 17 (-80.46%)
Mutual labels:  socket-io
2019-15
Catch My Mind - 웹으로 즐길 수 있는 캐치마인드
Stars: ✭ 19 (-78.16%)
Mutual labels:  socket-io
jwt-cli
A shell library to decode JWT tokens
Stars: ✭ 41 (-52.87%)
Mutual labels:  json-web-token
gcp auth
Minimal authentication library for Google Cloud Platform (GCP)
Stars: ✭ 42 (-51.72%)
Mutual labels:  auth
harker-bell
Official bell schedule app
Stars: ✭ 41 (-52.87%)
Mutual labels:  socket-io
realtime-geolocation
Geolocation tracking app with Node.js, Socket.io, & AngularJS
Stars: ✭ 29 (-66.67%)
Mutual labels:  socket-io
unite
Microsoft Engage 2021 - Video Conferencing Application
Stars: ✭ 143 (+64.37%)
Mutual labels:  socket-io
shikshak
Academics made Affordable.
Stars: ✭ 16 (-81.61%)
Mutual labels:  socket-io

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].