We’ll learn how to utilize JWT in Node.js to secure endpoints and even authenticate users in this blog.
Writing code and developing applications is quite simple. However, how do we handle authentication and, more importantly, authorization?
You’ll need the following items to follow along with this tutorial:
Setup nodejs project and add a basic setup in your project. I can start to implement register and login functionality.
In our application, we’ll build these two routes. Before putting the credentials in your database, we’ll use JWT to sign them and bycrypt to encrypt them (at the moment, I’ll use console.log()).
We’ll do the following with the /register route:
Before the start implement on the project. we need to add npm packages to our node js project.
npm install jsonwebtoken npm install bcryptjs
Add dependencies in the app.js file
const jwt = require('jsonwebtoken'); const bcrypt = require('bcrypt');
..// app.post("/register", async (req, res) => { try { // get user input const { first_name, last_name, email, password } = req.body; // Validate user input if (!(email && password && first_name && last_name)) { res.status(400).send("All input is required"); } // check if user already exist // Validate if user exist in our database //const oldUser = callyourDbfunction(); //if (oldUser) { // return res.status(409).send("User Already Exist."); //} //Encrypt user password encryptedPassword = await bcrypt.hash(password, 10); console.log("Encrypted Password", encryptedPassword); // save the user in the database. // Create token const token = jwt.sign( { user_id: user._id, email }, 'YOURSECRETKEY', { expiresIn: "2h", } ); // save user token user.token = token; // return new user res.status(201).json(user); } catch (err) { console.log(err); } });
Using Postman to test the endpoint.
We’ll do the following with the /login route:
..// app.post("/login", async (req, res) => { try { // Get user data const { email, password } = req.body; // Validate user input if (!(email && password)) { res.status(400).send("All input is required"); } // Validate if user exist in our database const user = finduserbymail(email); if (user && (await bcrypt.compare(password, user.password))) { // Create token using jwt const token = jwt.sign( { user_id: user._id, email }, 'YOURSECRETKEY', { expiresIn: "2h", } ); // save the token in user response user.token = token; res.status(200).json(user); } res.status(400).send("Invalid Credentials"); } catch (err) { console.log(err); } });
Using Postman to test the endpoint.
We’ve created and logged in a user successfully. Regardless, we’ll create a route that requires a user token in the header, which will be the JWT token we generated before.
Inside auth.js, add the following line.
const jwt = require("jsonwebtoken"); const verifyToken = (req, res, next) => { const token = req.body.token || req.query.token || req.headers["x-access-token"]; if (!token) { return res.status(403).send("A token is required for authentication"); } try { const decoded = jwt.verify(token, 'YOURSECRETKEY'); req.user = decoded; } catch (err) { return res.status(401).send("Invalid Token"); } return next(); }; module.exports = verifyToken;
To test the middleware, create the /welcome route and edit app.js with the following code.
const auth = require("./auth"); app.post("/welcome", auth, (req, res) => { res.status(200).send("Hello world"); });
That’s it. you can add the token in the header with the key x-access-token
.
I hope you guys understand how I can do this. Let me know if you face any difficulties.
You can watch my previous blog here.
Happy Coding {;}
In this article, we have to show Create and Used PIPE in angular
In this article, we have to show Create and Used PIPE in angular
In this article, we have to show Create and Used PIPE in angular