While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.

Introduction

Many web applications and APIs use a form of authentication to protect resources and restrict their access only to verified users. This guide will walk you through how to implement authentication for an API using Json Web Tokens (JWTs) and Passport, an authentication middleware for Node.

Understanding JSON Web Tokens

JSON Web Token (JWT) is an open standard that defines a compact and self-contained way for securely transmitting information between parties as a JSON object.

JWTs are secure because they are digitally signed and if the information
contained within is tampered in any way, it renders that token invalid. We’ll look at how this is made possible later on. J

A JWT is composed of three separate definitions: header, payload, and signature.

Header : the header defines the type of algorithm used to verify the token and the type of token:

     {
        "type" : "JWT",
        "alg" : "HS256"
      }

*Payload *: contains the claims. Claims are information about the user together with other additional metadata, such as the following:

     {
        id : 1
        name : 'devgson'
        iat : 1421211952
      }

Signature : The signature encodes the information in the header and payload in base64
format together with a secret key. All this information is then signed by the algorithm specified in the header. In our example, we’re using HMACSHA256. The signature verifies that the message being sent wasn’t tampered along the way.

     HMACSHA256(
        base64UrlEncode(header) + "." +
        base64UrlEncode(payload),
        secret
      )

Note: JWT’s should not be used to transfer or store secure information, because anyone that manages to intercept the token can decode the header and payload within. All the signature does is verify that the token hasn’t been tampered in any way. It doesn’t stop the token from being tampered with.

Setting up Passport

Passport is an authentication middleware used to authenticate requests. It allows developers to use different strategies for authenticating users, such as using a local database or connecting to social networks through APIs. In this guide, we’ll be using the local (email / password) strategy.

Lets create a folder structure for the files we’ll be using :

    -model
    ---model.js
    -routes
    ---routes.js
    ---secure-routes.js
    -auth
    ---auth.js
    -app.js
    -package.json

Install the necessary packages with:

  • npm install --save bcrypt body-parser express jsonwebtoken mongoose passport passport-local passport-jwt

We’ll need bcrypt for hashing user passwords, jsonwebtoken for signing tokens, passport-local for implementing local strategy, and passport-jwt for getting and verifying JWTs.

Here’s how our application is going to work :

  • The user signs up and then logs in, after the user logs in, a JSON web token would be given to the user.
  • The user is expected to store this token locally.
  • This token is to be sent by the user when trying to access certain secure routes, once the token has been verified, the user is then allowed to access the route.

Setting Up the Database

First of all, we’ll create the user schema. A user should only provide email and password, that would be enough information.

model/model.js

const mongoose = require('mongoose')
const bcrypt = require('bcrypt');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
  email : {
    type : String,
    required : true,
    unique : true
  },
  password : {
    type : String,
    required : true 
  }
});
  ...

Now we don’t want to store passwords in plain text because if an attacker manages to get access to the database, the password can be read so we want to avoid this. We’ll make use of a package called ‘bcrypt’ to hash user passwords and store them safely.

model/model.js
 ....
//This is called a pre-hook, before the user information is saved in the database
//this function will be called, we'll get the plain text password, hash it and store it.
UserSchema.pre('save', async function(next){
  //'this' refers to the current document about to be saved
  const user = this;
  //Hash the password with a salt round of 10, the higher the rounds the more secure, but the slower
  //your application becomes.
  const hash = await bcrypt.hash(this.password, 10);
  //Replace the plain text password with the hash and then store it
  this.password = hash;
  //Indicates we're done and moves on to the next middleware
  next();
});

//We'll use this later on to make sure that the user trying to log in has the correct credentials
UserSchema.methods.isValidPassword = async function(password){
  const user = this;
  //Hashes the password sent by the user for login and checks if the hashed password stored in the 
  //database matches the one sent. Returns true if it does else false.
  const compare = await bcrypt.compare(password, user.password);
  return compare;
}

const UserModel = mongoose.model('user',UserSchema);

module.exports = UserModel;

Setting Up Registration and Login Middleware

We’ll use the passport local strategy to create middleware that will handle user registration
and login. This will then be plugged into certain routes and be used for authentication.

auth/auth.js

const passport = require('passport');
const localStrategy = require('passport-local').Strategy;
const UserModel = require('../model/model');

//Create a passport middleware to handle user registration
passport.use('signup', new localStrategy({
  usernameField : 'email',
  passwordField : 'password'
}, async (email, password, done) => {
    try {
      //Save the information provided by the user to the the database
      const user = await UserModel.create({ email, password });
      //Send the user information to the next middleware
      return done(null, user);
    } catch (error) {
      done(error);
    }
}));

//Create a passport middleware to handle User login
passport.use('login', new localStrategy({
  usernameField : 'email',
  passwordField : 'password'
}, async (email, password, done) => {
  try {
    //Find the user associated with the email provided by the user
    const user = await UserModel.findOne({ email });
    if( !user ){
      //If the user isn't found in the database, return a message
      return done(null, false, { message : 'User not found'});
    }
    //Validate password and make sure it matches with the corresponding hash stored in the database
    //If the passwords match, it returns a value of true.
    const validate = await user.isValidPassword(password);
    if( !validate ){
      return done(null, false, { message : 'Wrong Password'});
    }
    //Send the user information to the next middleware
    return done(null, user, { message : 'Logged in Successfully'});
  } catch (error) {
    return done(error);
  }
}));
    ....

Creating the Routes

Now that we have middleware for handling registration and login, let’s create routes that’ll use this middleware.

routes/routes.js
const express = require('express');
const passport = require('passport');
const jwt = require('jsonwebtoken');

const router = express.Router();

//When the user sends a post request to this route, passport authenticates the user based on the
//middleware created previously
router.post('/signup', passport.authenticate('signup', { session : false }) , async (req, res, next) => {
  res.json({ 
    message : 'Signup successful',
    user : req.user 
  });
});

    ...

Signing the JWT

When the user logs in, the user information is passed to our custom callback which in
turn creates a secure token with the information. This token is then required to be passed along as a query parameter when accessing secure routes(which we’ll create later).

routes/routes.js
    ....
router.post('/login', async (req, res, next) => {
  passport.authenticate('login', async (err, user, info) => {     try {
      if(err || !user){
        const error = new Error('An Error occurred')
        return next(error);
      }
      req.login(user, { session : false }, async (error) => {
        if( error ) return next(error)
        //We don't want to store the sensitive information such as the
        //user password in the token so we pick only the email and id
        const body = { _id : user._id, email : user.email };
        //Sign the JWT token and populate the payload with the user email and id
        const token = jwt.sign({ user : body },'top_secret');
        //Send back the token to the user
        return res.json({ token });
      });     } catch (error) {
      return next(error);
    }
  })(req, res, next);
});

module.exports = router;

Note: We set { session : false } because we don’t want to store the user details in a session. We expect the user to send the token on each request to the secure routes. This is especially useful for API’s, but it’s not a recommended approach for web application for performance reasons.

Verifying the user token

So now we’ve handled user signup and login, the next step is allowing users with tokens access certain secure routes, but how do we verify that the token sent by the user is valid and hasn’t been manipulated in some way or just outright invalid. Let’s do that next.

auth/auth.js
  ....
const JWTstrategy = require('passport-jwt').Strategy;
//We use this to extract the JWT sent by the user
const ExtractJWT = require('passport-jwt').ExtractJwt;

//This verifies that the token sent by the user is valid
passport.use(new JWTstrategy({
  //secret we used to sign our JWT
  secretOrKey : 'top_secret',
  //we expect the user to send the token as a query parameter with the name 'secret_token'
  jwtFromRequest : ExtractJWT.fromUrlQueryParameter('secret_token')
}, async (token, done) => {
  try {
    //Pass the user details to the next middleware
    return done(null, token.user);
  } catch (error) {
    done(error);
  }
}));

Note : If you’ll need extra or sensitive details about the user that are not available in the token, you could use the _id available on the token to retrieve them from the database.

Creating secure routes

Now lets create some secure routes that only users with verified tokens can access.

routes/secure-routes.js
const express = require('express');

const router = express.Router();

//Let's say the route below is very sensitive and we want only authorized users to have access

//Displays information tailored according to the logged in user
router.get('/profile', (req, res, next) => {
  //We'll just send back the user details and the token
  res.json({
    message : 'You made it to the secure route',
    user : req.user,
    token : req.query.secret_token
  })
});

module.exports = router;

So now we’re all done with creating the routes and authentication middleware, let’s put everything together and then test it out.

app.js

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const passport = require('passport');
const app = express();
const UserModel = require('./model/model');

mongoose.connect('mongodb://127.0.0.1:27017/passport-jwt', { useMongoClient : true });
mongoose.connection.on('error', error => console.log(error) );
mongoose.Promise = global.Promise;

require('./auth/auth');

app.use( bodyParser.urlencoded({ extended : false }) );

const routes = require('./routes/routes');
const secureRoute = require('./routes/secure-route');

app.use('/', routes);
//We plugin our jwt strategy as a middleware so only verified users can access this route
app.use('/user', passport.authenticate('jwt', { session : false }), secureRoute );

//Handle errors
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.json({ error : err });
});

app.listen(3000, () => {
  console.log('Server started')
});

Testing with Postman

Now that we’ve put everything together, let’s use postman to test our API authentication. First of all we’ll have to sign up with an email and password. We can send over these details through the Body of our request. When that’s done, click the send button to initiate the POST request.
Testing with Postman
We can see the password is encrypted, therefore anyone with access to the database will have access to only the hashed password, we added ten(10) salt rounds to increase the security. You can read more about this here.
Let’s now login with the credentials and get our token. Visit the /login route, passing the email and password you used previously and then initiate the request.

Testing with Postman login

Now we have our token, we’ll send over this token whenever we want to access a secure route. Let’s try this by accessing a secure route user/profile, we’ll pass our token in a query parameter called secret_token, The token will be collected, verified and we’ll be given access to the route if it’s valid.

Testing with Postman valid token

As you can see, the valid token enables us gain access to the secure route. You could go ahead and try accessing this route but with an invalid token, the request will return an Unauthorized error.

Conclusion

JSON web tokens provide a secure way for creating authentication for APIs. An extra layer of security can be added by encrypting all the information within the token, thereby making it even more secure. Some resources for learning about JWT’s in depth include :

0 Comments

Creative Commons License