Simple Authentication in Node/Express using JWT (JSON Web Tokens)

You might have some routes you wanna protect or display information based on a given user’s account info. A simple way to restrict access on the backend with Node and Express is using JSON Web Tokens. In a later tutorial I’ll demonstrate how this can carry over to the front-end in frameworks such as AngularJS in order to get specific information about that token (user credentials, database info, etc).

There are many NPM modules that handle JSON web tokens, and many work fine. However, in this tutorial we will be using ‘jsonwebtokens’. Simply run ‘npm install jsonwebtokens’ in your project directory and require it in your desired page as following:

var User = require('./userModel');
var jwt = require('jsonwebtokens');
var newUser = function (req, res){
User.findOne({where:{ username: req.body.username }})
.then(function (user) {
if(!user){
User.create({
username: req.body.username,
password: req.body.password,
email: req.body.email
})
.then(function(user){
var myToken = jwt.sign({ user: user.id },
'secret',
{ expiresIn: 24 * 60 * 60 });
res.send(200, {'token': myToken,
'userId': user.id,
'username': user.username });
});
} else {
res.status(404).json('Username already exist!');
}
})
.catch(function (err) {
res.send('Error creating user: ', err.message);
});
};

In this example, it shows your basic new user sign up function, something you might find on a userController page in the back-end of a Node project with an ORM. This piece of code is from a project I worked on a few months ago and the user model is an instance of Sequelize, a MySQL ORM.

As you can see, if the user doesn’t exist, it is created. Shortly after we declare a variable called ‘myToken’ that stores the very specific token including the ‘secure’ information in the first parameter, a secret string (which can be anything) in the second parameter, and an optional object that takes parameters such as expiration of the token in the third parameter.

Once the token is signed, we send the token as a property in the response object being sent to the client side. In a future tutorial I’ll demonstrate how I often handle that with AngularJS.

Verifying JSON Web Tokens

var authorize = function(req, res, next) {
var token = req.body.token || req.headers[‘x-access-token’];
  if (token) {
jwt.verify(token, 'secret', function(err, decoded) {
if (err) {
console.error(‘JWT Verification Error’, err);
return res.status(403).send(err);
} else {
req.decoded = decoded;
return next();
}
});
} else {
res.status(403).send(‘Token not provided’);
}
}

In this example, it’s a pretty simple implementation of a middleware function that can be used before allowing access to another route.

This time, we still use jwt, but instead of signing the tokens we use a built-in method called ‘verify’ that checks if the token being passed in matches the secret (which can be anything). If it does then the callback function returns a variable, in our case ‘decoded’ that will either evaluate to truthy or falsy.

On the client side, in order for the middleware to know if a route is authenticated you must manually set the headers.

headers[‘x-access-token’] = [jwt-token]

Is it secure? Yes. Because the JWT is encrypted and the secret isn’t being passed to the front-end. Read more here: https://github.com/auth0/jwt-decode/issues/4

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.