Generating the token

We will use an NPM module to generate JWT called jsonwebtoken. Open a new console and write the following command into the wc-backend folder to install the module:

$ npm install jsonwebtoken --save

Once the installation is finished. Open security-api.js, and let's import our library, as follows:

const express = require('express')
const jwt = require('jsonwebtoken')
const api = express.Router()

...

With our dependency imported in our file, let's implement the generateToken function. Apply the following changes:

...
const logIn = (username, password) => {
if (username == 'admin' && password == 'admin') {
let userData = {
name: "Admin"
}
return generateToken(userData)
} else {
return null
}
}

const generateToken = userData => {
return jwt.sign(userData, "s3cret", { expiresIn: '3h' })
}

...

That's all! Let's understand the code. We call the sign function of the jwt object to create our token. We pass the following information to the function:

  • userData: The piece of information we want to tokenize
  • secret: A secret value that is used to encrypt and validate the token
  • expiration: The expiration date of the token

Now we are ready with the authentication logic. To finish our implementation, we have to make this logic available via our REST Controller.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset