Node.js Authentication with JWT

What is a JSON WEB TOKEN?

JWT (JSON WEB TOKEN) is a standard that defines a compact and self-contained way for securely trasmitting information between parties as a JSON object.


Why JWT?

There are several reasons why applications use JWT for authentication:

  • JWT is a good choice to be passed in HTML and HTTP environments due to its smaller footprint when compared to other types of tokens.
  • JWT can be signed using a shared secret and also by using public/private key pairs.
  • It is easier to work with JWT as JSON parsers are common in most programming 

languages.

  • JWT is also suitable for implementing authorization in large-scale web applications.


Structure of a JWT

  • Header - Consist of two parts: - Type of token, i.w JWT - Signing algorithm, example SHA512
  • Payload - Contains the claims that provide information about a user who has been authenticated along with other information like token expiry time

example

{

 "sub": "0987654321",

 "name": "Jonh Doe",

 "admin": true 


  • Signature - Final part of a token that wraps in the encoded header and payload, along with the algorithm and a secret

example: 

HMACSHA512(base64UrlEnconde(header)+"."+base64UrlEncode(payload), secret) 



JWT USE CASES

  • Authorization - This is the most common scenario for using JWT. Once the User is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token.
  • Information Exchange - JWT are a good way of securely transmitting information between parties.


DEMO CODE

For this demo it is necessary to install express and jsonwebtoken libraries. You can install with the following code: npm install express jsonwebtoken

After the installation create a file called app.js and add the code bellow. This code contains some comments to help you understand.

const express = require('express')

const jwt = require('jsonwebtoken')


const app = express();


app.get('/api', (req, res) => {

    res.json({

        message: 'Hey There! Welcome to API'

    });

});

//It is possible to add a post only if we have a token from the login

app.post('/api/posts', verifyToken, (req, res) => {

    jwt.verify(req.token, 'secretkey', (err, authData) => {

        if(err){

            res.sendStatus(403)

        } else {

            res.json({

                message: 'Post created...',

                authData

            });

        }

    })

   

});

//LOGIN - if the login is correct it will create a token

app.post('/api/login', (req, res) => {

    const user = {

        id: 1,

        username: 'Jonh',

        email:'jonh@mail.com'

    }

    jwt.sign({user:user}, 'secretkey', (err, token) => {

        res.json({

            token,

        });

    });

});

//Verify if the token exists

function verifyToken(req, res){

    const bearerHeader = req.headers['authorization'];

    if(typeof bearerHeader !== 'undefined'){

        const bearerToken =  bearerHeader.split(' ')[1];

        req.token =  bearerToken;

        next();

    } else {

        res.sendStatus(403);

    }

}


app.listen(5000, (req, res) => {

    console.log('server is running on port 5000')

});




To view or add a comment, sign in

More articles by Daniel Albino

  • Webpack - Module Bundler

    Nowadays, as a Frontend Developer, we use a lot of tools and new libraries to work on our projects and, sometimes, the…

  • Frontend Performance

    In today's digital world, there are millions of websites that are accessed every day for a variety of reasons. However,…

  • Frontend Accessibility

    In this article we will talk about the importance of accessibility on web pages. The web pages must be developed taking…

  • Create a Blockchain using Python

    Currently we have been talking about blockchain and cryptocurrencies in our daily lifes. But what is blockchain? A…

  • Generate NTF images with Python

    Imagine buying a digital artwork on the internet at a reasonable price and getting a unique digital token known as an…

Insights from the community

Others also viewed

Explore topics