umma.dev

JWT Tokens in Node.js APIs

This post is about adding authentication via Json Web Tokens (JWT) with Node.js. On the front-end you can pass the JWT token and ensure that data stays safe, such as passwords and log in credentials.

What are JWT tokens?

JWT tokens enable you to be able to transfer information within an api in a secure manner.

How to Incorporate JWT tokens into a Node.js API

  • Create a new directory

mkdir <directory-name>

  • Navigate to your code editor and open up the folder. If you are using VS Code you can open up a terminal via view -> terminal

Run the command npm init

  • Install JWT and Express into your project

npm install express jsonwebtoken

  • You should be able to see the following files in your directory: package.json and package-lock.json

  • Create a file called index.js in the root of your folder

Insert the following code into the file.

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

app.get('/api', function(req, res) {
    res.json({
        text: 'my api'
    })
})

app.post('/api/login', function(req, res) {
    //fake user
    const user = { id:1 };
    const token = jwt.sign({ user }, 'secretkey');
    return.json({
        token:token
    })

})

app.get('/api/protected', ensureToken, function(req, res) {
    jwt.verify(req.token, 'secretkey', function(err, data) {
        if(err) {
            res.sentState(403);
        } else {
            res.json({
                text: 'thisis protected',
                data: data
            })
        }
    })
})

function ensureToken(req, res, next) {
    const bearerHeader = req.headers["authorization"];
    if(typeof bearerHeader !== 'undefined') {
        const bearer = bearHeader.split(" ");
        const bearerToken = bearer[1];
        req.token = bearerToken;
        next();
    } else {
        res.sendStatus(403);
    }
}

app.listen(3000, function() {
    console.log('App listening on port 3000');
})