Authenticating Node.js using JSON Web Token (Part-2)

As a follow up on basic authentication on JSON web token post. Today, let’s see about the sample implementation of JWT.

prerequisite:

Install the below packages in your server.js file.

1) express.js
2) body-parser
3) jsonwebtoken

npm install express body-parser jsonwebtoken

Implementation:

Before start integrating the JWT, just create the basic skeleton structure of server.js. Check out the Node.js HTTP response post to know how the request and response works.

Here we go! In the below sample code I have created the simple server.js file to authenticate the root folder. With the below script anyone can access the res.json file.

var express = require('express');
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
var app = express();
app.use(bodyParser.json());

app.get('/', function (req, res) {
    res.json({
        message: 'Permission Granted!'
    });
});

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

Now create the token to authenticate the root folder by passing the user id with the secret key. You can connect to the database and authenticate it for demo purpose I have hardcoded the user id.

complete: return an object with the decoded payload and header.

Pass the authorization token for the blog page to authenticate the Token.

app.get('/blog', getToken, function (req, res) {
  console.log("req"+req);
  jwt.verify(req.token, 'HybrdAppZone</>', function(err, data) {
    if (err) {
        res.sendStatus(403);
        console.log("err: "+err);
    } else {
        res.json({
        message: 'Protected information',
        data: data
      });
    }
  });
}); 

The above getToken() function helps to authenticate the bearer token.

function getToken(req, res, next) {
  const bearerHeader = req.headers["authorization"];
  console.log("Headers: "+JSON.stringify(req.headers)); 
  if (typeof bearerHeader !== 'undefined') {
    const bearer = bearerHeader.split(" ");
    const bearerToken = bearer[1];
    req.token = bearerToken; 
    next();
  } else {
    res.sendStatus(403);
    console.log("bearerToken error: "+bearerHeader);  
  }
} 

Test your Application:

To test the API try using Postman or REST API client extension which will be available in the chrome store.

STEP 1: First add the url with the GET method and generate the token by clicking the send button in the Postman.

STEP 2: Next to access the /blog page url and add the Authorization token which was generated before. Onclick submit button you can see the forbidden page.

STEP 3: Try by changing the bearer token and then you will be able to see the URL is forbidden.

Please comment below if you have any other queries.

Download Code
Execute Code
By | 2018-01-11T17:59:54+00:00 January 7th, 2018|express.js|6 Comments

6 Comments

  1. 79Zulma September 26, 2019 at 3:12 am

    I can see that your website probably doesn’t have much visits.

    Your posts are interesting, you only need more new readers.
    I know a method that can cause a viral effect on your blog.
    Search in google: Jemensso’s tricks

  2. 역삼안마 October 25, 2019 at 5:54 am

    I am extremely impressed with your writing skills as well as
    with the layout on your weblog. Is this a paid theme or did you customize it yourself?
    Anyway keep up the excellent quality writing, it is rare to see a great
    blog like this one nowadays.

  3. mama bear November 30, 2019 at 10:38 pm

    Appreciation to my father who shared with me on the topic of this blog, this weblog is really amazing.

  4. wormateio hacks December 2, 2019 at 2:10 pm

    I visit each day a few web pages and sites to read articles,
    but this web site offers quality based content.

  5. t shirt rug December 5, 2019 at 11:11 am

    You really make it appear so easy along with your presentation but
    I in finding this matter to be actually something that I think I’d by
    no means understand. It seems too complex and very
    large for me. I’m looking ahead to your next put up, I’ll attempt to get
    the dangle of it!

  6. ugly christmas sweater cheap December 5, 2019 at 9:03 pm

    Wow that was odd. I just wrote an incredibly long comment but after I clicked
    submit my comment didn’t show up. Grrrr… well I’m not writing all that over
    again. Anyways, just wanted to say great blog!

Leave A Comment

Get Amazing Tips!

Get MEAN stack updates delivered straight to your inbox, just a click away! Sign Up Now
First Name
Email address
Secure and Spam free...