18.10. Working with JSON Web Tokens (JWT) in NodeJS

JSON Web Tokens (JWT) is an open standard (RFC 7519) that defines a compact and secure way to pass information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

JWT-based authentication is a popular way to authenticate web applications. With JWT authentication, a token is stored on the client, which is sent on each request to the server to be authenticated.

How to implement JWT-based authentication in a NodeJS API

To implement JWT-based authentication in a NodeJS API, you will need the following steps:

  1. Install jsonwebtoken package
  2. Create a login route to generate the token
  3. Verify token on every request

1. Install jsonwebtoken package

First, you'll need to install the jsonwebtoken package in your NodeJS project. You can do this using npm (Node Package Manager) with the following command:

npm install jsonwebtoken

2. Create a login route to generate the token

Next, you'll need to create a login route that will generate the JWT token. Here is an example of how you can do this:

const jwt = require('jsonwebtoken');
const express = require('express');
const app = express();

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

    const user = {
        id: 1,
        username: 'test',
        email: 'test@test.com'
    }

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

In the example above, we authenticate the user first. We then use the jwt.sign function to create the JWT token. The jwt.sign function takes three parameters: the payload (in this case, the user object), the secret key, and a callback function.

3. Verify token on every request

Finally, you'll need to verify the JWT token on each request. You can do this by creating a middleware that verifies the token:

function authenticateToken(req, res, next) {
    const bearerHeader = req.headers['authorization'];

    if (typeof bearerHeader !== 'undefined') {
        const bearer = bearerHeader.split(' ');
        const bearerToken = bearer[1];
        req.token = bearerToken;
        next();
    } else {
        res.sendStatus(403);
    }
}

app.get('/api', authenticateToken, (req, res) => {
    jwt.verify(req.token, 'secretkey', (err, authData) => {
        if(err) {
            res.sendStatus(403);
        } else {
            res.json({
                message: 'API accessed successfully',
                authDate
            });
        }
    });
});

In the example above, the authenticateToken middleware checks whether the JWT token is present in the authorization header. If the token is present, it is verified using the jwt.verify function. If the token is valid, the request is allowed to proceed. If the token is not valid, an error status 403 (Forbidden) is sent.

And that's all you need to implement JWT-based authentication in a NodeJS API!

Now answer the exercise about the content:

What is required to implement JWT based authentication in a NodeJS API?

You are right! Congratulations, now go to the next page

You missed! Try again.

Article image Data validation with the Joi package

Next page of the Free Ebook:

120Data validation with the Joi package

5 minutes

Obtenez votre certificat pour ce cours gratuitement ! en téléchargeant lapplication Cursa et en lisant lebook qui sy trouve. Disponible sur Google Play ou App Store !

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text