Secured Web API using ExpressJS and JSON Web Token in Visual Studio

Author: Shahim Sadakath


Hi Guys,


This time I created a secured Web API using ExpressJS and JSON Web Token in Visual Studio. Hope you guys like it.


1) Create Express JS Web Application in Visual Studio

 


2) Add jsonwebtoken by right clicking on npm -> Install new npm Packages

 

3) Create a file named api.js which will be our secured api and paste the following code

'use strict';

var express = require('express');

var router = express.Router();

var jwt = require('jsonwebtoken');


/* GET home page. */

router.get('/', function (req, res) {

    res.render('index', { title: 'API' });

});


//Login method to get the token

router.post('/login',  function (req, res) {

    let user = { id: 3 };

    let token = jwt.sign(user, 'app_secret');

    res.json({ token:token });

});


//our protected resource

router.get('/protected', ensureToken, function (req, res) {

    jwt.verify(req.token, 'app_secret', function (err, data) {

        if (err)

            res.sendStatus(403);

        else

        {

            res.json({ text: "Protected Content" });

        }


    })

    

});


//Function to check whether token available when calling protected reseource

function ensureToken(req, res, next)

{

    let bearerHeader = req.headers["authorization"];

    if (typeof bearerHeader !== 'undefined')

    {

        let bearer = bearerHeader.split(" ");

        let bearerToken = bearer[1];

        req.token = bearerToken;

        next();

    }

    else

    {

        res.sendStatus(403);

    }


}


module.exports = router;


4) Register the api in app.js as following 

var api = require('./routes/api');


...


var app = express();


app.use('/api', api);


5) First we will call the protected method without any tokens

 


As expected it returns Forbidden (403)


6) Now we will call the Login method to get the token

 

7) Now we will call the protected method with the Authorization token



Tags: JWT expressjs visualstudio
Views: 293
Register for more exciting articles

Comments

Please login or register to post a comment.


There are currently no comments.