InterviewSolution
| 1. |
How to generate a token using JWT in Express app? |
|
Answer» JWT stands for JSON WEB Tokens. They are a very SECURE way of AUTHENTICATION of the client with the server. Let's look at an example, where we will get the JWT TOKEN of a specific user. We will be generating it on the server and sending it back to the client. Each client will have a unique JWT token. We will first set up the Express JS application by creating a Node.js runtime, through npm init -y command. After that we are installing express, jsonwebtoken and dotenv in it through npm i express jsonwebtoken dotenv command. Next, create an .env file and give a TOKEN_SECRET in it. We can use any long random string in it. Now, create an app.js file. Here, we are first doing the required imports of express, jwt and dotenv. After that we are using the express.json and the dotenv. Next, we have a POST route with /api/create. Here, we are passing the username to a generateAccessToken() to receive the token and after that sending it back to the client in res.json() Now, in the generateAccessToken() FUNCTION, we are using jwt.sign() and taking the username, our TOKEN_SECRET and expiry time to generate the JWT token. After starting the server in terminal with node app.js, we will open Postman and do a POST request to http://localhost:3000/api/create with the username as JSON and we will receive our unique JWT token. |
|