SocketIO JWT Auth
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, andsucceedWithoutToken
, which, iftrue
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, anddone
is an error-first callback with three args:done(err, user, message)
var io = ;var jwtAuth = ; // using middlewareio;
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 = ;var jwtAuth = ; // using middlewareio;
Access user info
io; io;
Client Side
<script> // You should add auth_token to the query when connecting // Replace THE_JWT_TOKEN with the valid one var socket = ; // 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; // Connection succeeded socket</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 = ; // ...</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
Copyright (c) 2015 Lei Lei