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: 'imsonujangra@gmail.com',
        id: 1,
        name: 'Sonu Jangra'
    };
    // sign with default (HMAC SHA256) 
    const token = jsonWebToken.sign(user, myJWTSecretKey);
    res.json({
        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) {
        res.json({
            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.


{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImFyanVucGhwQGdtYWlsLmNvbSIsImlkIjoxLCJuYW1lIjoiQXJqdW4gQSIsImlhdCI6MTQ5OTM2NjM0NH0.xRJo4je_4QIyqJpyes8ixxekTqI2EQ6v8_zW3YuG_tE"}


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

http://localhost:3000/verify/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImFyanVucGh

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


{"error":false,"data":{"email":"imsonujangra@gmail.com","id":1,"name":"Sonu Jangra","iat":1299366344}}



No comments:

Post a Comment

Download the eBook of react js for beginners

ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications...

Popular