Authenticating Node.js with JWT

Authenticating Node.js with JWT

In this blog, we will go through a simple example of how to implement JWT authentication in a NodeJS API using express with JavaScript.

So, let's start with some basics first.

What is JSON Web Tokens (JWT)?

JSON web tokens are text strings that can be used by client and server to authenticate and share information easily. If you remember the necessary authentication, we do write information to the client by writing the cookie as a session variable.

The JWT Claims Set represents a compact URL-safe JSON object, that is base64url encoded and digitally signed and/or encrypted. The JSON object consists of zero or more name/value pairs (or members), where the names are strings and the values are arbitrary JSON values. 

JSON Web Tokens consist of three parts separated by dots(i.e. header.payload.signature)

How JWT works?

JWT works as a two way protocol where a request is made and the response is generated from a server.

No alt text provided for this image

The browser or the requesting device makes the request(user login information for authentication) for JWT encoded data, the server generates the signed token and return to the client(Mobile device/browser) as shown in the diagram above.

Subsequently, the token can be sent over to the http request for every other request that needs authentication on the server. The server then validates the token and, if it’s valid, returns the secure resource to the client.This token is often signed using any secure signature method (e.g Asymmetric key algorithm such as HMAC SHA-256 or Asymmetric, public-key system, such as RSA).

So, let's start to implement JWT using nodejs with express.

First we need to install dependencies like express, body-parser and jsonwebtoken using bellow command.

npm install express body-parser jsonwebtoken --save

After installed packages package.json file look like:

package.json

{
  "name": "node-jwt",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "BoB",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.3",
    "express": "^4.16.4",
    "jsonwebtoken": "^8.4.0"
  }
}

Start out by adding a new file in the root directory of the project. Give it a name of config.jsHere you’ll put configuration settings for the application. Everything we need at the moment is just to define a secret key for our JSON Web Token.

config.js

{
    "secret": "some-secret-shit-goes-here",
    "refreshTokenSecret": "some-secret-refresh-token-shit",
    "port": 3000,
    "tokenLife": 900,
    "refreshTokenLife": 86400
}

Now, We have all basic thing to configure the node app. So lets create a new file in the root directory of the project. Give it a name of tokenChecker.js. tokenChecker file used to verify the jwt token with return response as per the token verification process.

tokenChecker.js

const jwt = require('jsonwebtoken')
const config = require('./config')


module.exports = (req,res,next) => {
  console.log(req.body.token);
  const token = req.body.token || req.query.token || req.headers['x-access-token']
  // decode tokenif (token) {// verifies secret and checks exp
    jwt.verify(token, config.secret, function(err, decoded) {
        if (err) {
            return res.status(401).json({"error": true, "message": 'Unauthorized access.' });
        }
      req.decoded = decoded;
      next();
    });
  } else {
    // if there is no token// return an errorreturn res.status(403).send({"error": true,
        "message": 'No token provided.'
    });
  }
}

In above code we have import jsonwebtoken module as jwt. Get post as token from the request to check the passed token is valid or not .

By using jwt.verify method we have check that particular token is valid or not. If token is valid then we execute the next request by using next() method. If the token not valid the we send then json response with message as "Unauthorized access".

Now we have implement code for toke verification into the tokenChecker.js file. So we will start to create node app server and post route and use tokenchecker.js file as middleware with routing.

So, let's start to create entry point of app.js file and define routing with middleware to check token authorization.

app.js

const express = require('express')
const bodyParser = require('body-parser')
const jwt = require('jsonwebtoken')
const router = express.Router()
const config = require('./config')
const tokenList = {}
const app = express()


//base route for node app
router.get('/', (req,res) => {
    res.send('Ok');
})

// login routing for user login
router.post('/login', (req,res) => {
    const postData = req.body;
    const user = {
        "email": postData.email,
        "name": postData.name
    }
    // do the database authentication here, with user name and password combination.const token = jwt.sign(user, config.secret, { expiresIn: config.tokenLife})
    const refreshToken = jwt.sign(user, config.refreshTokenSecret, { expiresIn: config.refreshTokenLife})
    const response = {
        "status": "Logged in",
        "token": token,
        "refreshToken": refreshToken,
    }
    tokenList[refreshToken] = response
    res.status(200).json(response);
})

// token routing for refresh the existing token. 
router.post('/token', (req,res) => {
    // refresh the damn tokenconst postData = req.body
    // if refresh token existsif((postData.refreshToken) && (postData.refreshToken in tokenList)) {
        const user = {
            "email": postData.email,
            "name": postData.name
        }
        const token = jwt.sign(user, config.secret, { expiresIn: config.tokenLife})
        const response = {
            "token": token,
        }
        // update the token in the list
        tokenList[postData.refreshToken].token = token
        res.status(200).json(response);        
    } else {
        res.status(404).send('Invalid request')
    }
})

// use tokenChecker module as middleware here
router.use(require('./tokenChecker'))

//configure body parser to easily get the post data form request.
app.use(bodyParser.json())
app.use('/api', router)
// create server listing port as 3000
app.listen(config.port || process.env.port || 3000, console.log('running'));

In above app.js file we first import the required module as express, body-parser and jsonwebtoken. Then we have import config.js file and tokenChecker.js file.

We have created two post route name login and token. Into the login post route getting request data using body-parser and then sign the jwt using jwt.sign() method by passing the config settings and also same thing for token post route.

token post route are defined to refresh the old token and updated token insert into the tokenList array.

Then we use tokenChecker as middleware to verify the token and then set the defined routes against /api routes.

Finally, We create the node app server listing with port 3000.

So, Using postmen we will check the user are reauthorized or not using JWT.

No alt text provided for this image

Now, we have successfully integrated the JWT.

Finally, How To Use JWT To Authenticating User In Node.js with JWT Example is over.

Thanks You!


要查看或添加评论,请登录

Baburao Shelvane的更多文章

  • Creating ReactJS APP

    Creating ReactJS APP

    What is React JS? ReactJS is an open-source JavaScript library which is used for building user interfaces specifically…

  • Understanding, creating and subscribing to observables

    Understanding, creating and subscribing to observables

    In this blog, we will learn to use the RxJS 6 library with Angular 6. We will learn about how to import the Observable…

  • Template Engines for Node.js

    Template Engines for Node.js

    In this blog, we will look at a comparison of different Node.js templating engines and go through the basics of Node.

    1 条评论
  • Understand Node.js Module

    Understand Node.js Module

    Module in Node.js is a simple or complex functionality organised in single or multiple JavaScript files which can be…

  • Creating Node.js Application Using Express

    Creating Node.js Application Using Express

    Before we begin, make sure you have a recent version of Node.js installed.

  • Basic concept of HTTP

    Basic concept of HTTP

    Hypertext Transfer Protocol (HTTP) is an application-layer protocol for transmitting hypermedia documents, such as…

    2 条评论
  • Input And Output Decorator

    Input And Output Decorator

    The main purpose of Input Output property is used in angular for passing data between component. Input : @Input…

  • Angular Directive

    Angular Directive

    A directive allows you to attach a behavior to DOM elements. This behavior could be as simple or as complex like.

  • Pipes usage

    Pipes usage

    “In Angular Pipe (|) operator is use to transform data before displaying it into the browser.Using pipe | operator we…

    2 条评论
  • Understand NgModule

    Understand NgModule

    "The NgModule is a TypeScript class marked by the @NgModule decorator.The purpose of a NgModule is to declare each…

社区洞察

其他会员也浏览了