worf.js
v2.2.4
Published
A node module that creates a middleware to authenticate against jwt
Downloads
6
Readme
Worf.js
A node module that provides functionalities to authenticate a user through JWT.
Usage
Methods
The module exposes the following methods:
setSecret(secret)
This method must be called once upon initialization in order to set the secret used to decode the JWT.
setTokenKey(key)
Optional, defines a custom key for the token. This will be the name of the cookie and the name of the query parameter that identify the token in a request (see Middleware below for more info).
encode(object, expiresIn, secret)
Returns a JWT for object
.
decode(token, secret)
Returns a decoded object from a JWT, if valid.
authenticate(options)
- Middleware
Worf provides a middleware to be used in Express-based applications. worf.authenticate(options)
returns the middleware function that can be configured via the options
parameter:
options.optional
: boolean, whether the middleware should let the request pass even if no valid token is found (in this case req.user is null). Default: falseoptions.require
: object, authenticates only if all fields in the decoded user object match those in require. e.g.:
worf.authenticate({ require : { id: 1, level : 'admin' } })
// only authorizes user with id 1 AND level 'admin' to access the route.
options.error
: number, overwrite response error code in case of user not authenticated (default: 403)options.secret
: object, overwrite secret for this specific routeoptions.secret.require
: tries to decode the token with this secret, disregarding global secret set via config.options.secret.alternative
: tries to decode the token with the global secret, then tries this alternative in case of failure. e.g.:
worf.authenticate({ secret : { require : 'xyz' } }) // only authorizes user with whose token was encode with secret 'xyz' worf.authenticate({ secret : { alternative : 'xyz' } }) // authorize users whose token was encoded either with global or 'xyz' secret
The middleware looks for a JWT token in the request, in order:
- In the token cookie
- In the Authorization header
- In a token parameter in the url query
If a valid token is found, req.user
is populated with the user data found int the token itself. Otherwise a 401 is returned.
Example:
var worf = require('worf.js');
var config = require('./secrets.json');
worf.setSecret(config.jwtsecret);
app.get('/some-route', worf.authenticate(), function(req, res){
console.log('User is autheticated with id ' + req.user.id);
});
app.get('/some-other-route', worf.authenticate({ optional: true}), function(req, res){
if(req.user) {
console.log('User is autheticated with id ' + req.user.id);
} else {
console.log("User is not autheticated, but it's fine anyway");
}
});
app.get('/john', worf.authenticate({ require : { username : 'john' } }), function(req, res){
console.log('User ' + req.user.id + ' is called john');
});
getUser(request)
Worf also exposes a getUser
function that takes the request as a parameter. If performs the same checks on the request as the middleware and returns a user object on success, null
otherwise.
Example - client:
var jwt = /* token */;
var socket = new WebSocket('ws://server:5000?token=' + jwt);
Example - server:
var worf = require('worf.js');
var WebSocketServer = require('ws').Server;
server = new WebSocketServer({ port: 5000 });
server.on('connection', function(socket){
var user = worf.getUser(socket.upgradeReq);
if(!user){
console.log('User not authenticated');
socket.close();
return;
}
console.log('User is autheticated wiht id ' + req.user.id);
});