Monday, 30 October 2017

Implementing authentication security in express with JWT

JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.It comprises a compact and URL-safe JSON object, which is cryptographically signed to verify its authenticity, and which can also be encrypted if the payload contains sensitive information.JWT.IO allows you to decode, verify and generate JWT.

Implementing security token in express.js

How to use jWT with express.js.

Create project directory and install required dependencies with below shown commands.

//create an folder express-jwt-tutorial
mkdir express-jwt-tutorial
//change the directory
cd express-jwt-tutorial
//It will create package.json file under the current directory
npm init --yes
// It will download all mentioned modules into node_modules directory
npm install --save express body-parser jsonwebtoken

Package Information :

express is the Node framework.
body-parser will let us pull POST content from our HTTP request.
jsonwebtoken is a library which will take care of generating and verifying

Now create a file called app.js in your directory.

// app.js
// importing express lib
const express = require('express');
// creating express instance
const app = express();
// importing body-parser, which will handle the user input bodies
const bodyParser = require('body-parser');
// importing jsonwebtoken module, this module will create and decode the JWT tokens.
const jsonWebToken = require('jsonwebtoken');
app.use(bodyParser.json()); // only parses json data
app.use(bodyParser.urlencoded({ // handles the urlencoded bodies
    extended: true
// set secret key, which we will use for creating and decoding JWT tokens, keep it safe. 
const myJWTSecretKey = 'my-secret-key'; 
app.get('/', (req, res) => {
    // get user object from the data source, Ex: database 
    const user = {
        email: '',
        id: 1,
        name: 'Sonu Jangra'
    // sign with default (HMAC SHA256) 
    const token = jsonWebToken.sign(user, myJWTSecretKey);
        token: token
// GET - http://localhost:3000/verify/{token}
app.get('/verify/:token', (req, res) => {
    try {
        const tokenDecodedData = jsonWebToken.verify(req.params.token, myJWTSecretKey);
        return res.json({
            error: false,
            data: tokenDecodedData
    } catch (error) {
            error: true,
            data: error
app.listen(3000, () => {
    console.log('Server is running at: 3000');

Now start the server using

node server.js and type this address in browser http://localhost:3000.

If everything fine you will see the below output.


You can verify and decode above token, by pointing your browser with token,


If everything goes well you should able to see below output:

{"error":false,"data":{"email":"","id":1,"name":"Sonu Jangra","iat":1299366344}}

Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts