Skip to main content

Command Palette

Search for a command to run...

Using JWT

Updated
2 min readView as Markdown

Simple JWT tutorial for quick start. Check out complete code at github .

npm init --y

Install npm dependencies

npm install --save express body-parser jsonwebtoken

Create app.js file and let's start with initialising the Express server.

const express = require("express");

const app = express();

app.listen("8082", function(){
    console.log("Server Started");
});

We will require body parser to parse the payload. Let's add body parser.

const express = require("express");
const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.json())

app.listen("8082", function(){
    console.log("Server Started");    
})

Let's add login and validate route which will be used to authenticate user information and validate the user respectively.

const express = require("express");
const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.json());

app.post("/login", function(req, res){
    //Authentication code goes here
});

app.post("/validate", function(req, res){
    //validate the user
});

app.listen("8082", function(){
    console.log("Server Started");    
})

Let's add final piece of the puzzle, JWT.

const express = require("express");
const bodyParser = require("body-parser");
const jwt = require("jsonwebtoken");
const SECRETE_KEY = "Test";

const app = express();

// parse application/json
app.use(bodyParser.json())

app.post("/login", function(req, res){
    const {username, password} = req.body;
    if(username === "amolkhatri" && password === "amolkhatri"){
        const token = jwt.sign({username, password}, SECRETE_KEY);
        res.send(200, {token});
    }
});

app.post("/validate", function(req, res){
    const {headers} = req;
    const authorization = headers.authorization;
    const token = authorization.split(" ")[1];
    let isValid = false;
    if(token){
        isValid = !!jwt.verify(token, SECRETE_KEY);
    }
    res.send(200, {isValid});
});

app.listen("8082", function(){
    console.log("Server Started");    
});