I am following a video tutorial on login authentication using JWT Tokens.
I made up a database on PostgreSQL, connected it with my Node JS server and tested out registration and login commands. Both the queries worked fine on Postman and Postman returned the expected results.
Now, on logging in, I get a JWT Token in returning value, which is to be used further to get the user ID who's logged in and his information.
So, to test if that token is working or not, I made a route which verifies if the user is logged in or not. (It is added in the same file in which login and registration routes are)
Code of this route file file is as follows (jwAuth.js). I have not added codes of Registration and Login in it
const router = require('express').Router()
const pool = require("../db")
const bcrypt = require("bcryptjs");
const jwtGenerator = require('../utils/jwtGenerator');
const authorization = require('../middleware/authorization');
// Registeration and Login Routes
// Verification Route
router.get("/is-verify", authorization, async (res, req) => {
try {
res.json(true);
} catch (err) {
console.log(err.message);
res.status(500).send("Server Error")
}
})
module.exports = router;
The code for the middleware authorization.js is as follows,
const jwt = require("jsonwebtoken");
require("dotenv").config();
module.exports = async (req, res, next) => {
try {
const jwtToken = req.header("token");
if (!jwtToken) {
return res.status(403).json("Not Authorized");
}
// In case we do have a token, check if the token is valid or not
const payload = jwt.verify(jwtToken, process.env.jwtSecret);
req.user = payload.user;
} catch (err) {
console.log(err.message);
return res.status(403).json("You are not authorized");
}
}
I also tried the same thing on another route, dashboard.js which was supposed to return/print the ID of the user using the JWT Token given to it, conditioned that the user is logged in correctly
The code of dashboard.js is as follows,
const router = require('express').Router()
const pool = require("../db")
const authorization = require("../middleware/authorization")
router.get("/", authorization, async (req, res) => {
try {
res.json(req.user);
} catch (err) {
console.log(err.message)
res.status(500).json("Server Error");
}
})
module.exports = router
And the code for my index.js (or server.js) is as follows,
const express = require('express')
const app = express()
const cors = require('cors')
app.use(express.json()) // Lets you use req.body
app.use(cors())
// ROUTES
// Register and Login Routes
app.use("/auth", require("./routes/jwAuth"));
app.use("/dashboard", require("./routes/dashboard"));
app.listen(3000, () => {
console.log("Console is running");
})
My problem is, If I try to send request to the following links with the required data, Postman works fine and data is also added in my database (and is also retrieved correctly while checking for login)
http://localhost:3000/auth/register
http://localhost:3000/auth/login
But when I try the same thing with this URL (by giving the JWT Token in the Header of the Postman GET Request,
http://localhost:3000/dashboard
http://localhost:3000/auth/is-verify
Postman gets stuck, takes a long time in processing the request and ultimately gives this error,
Could not get response Error: read ECONNRESET
I tried searching this error up and apparently the fix of this issue is adding an IP address of localhost in etc/hosts file but in that case, my registration and login POST Requests would not have worked either. I am unable to figure out the problem so kindly someone please help.
Just to be sure, I have shared below the etc/hosts file as well and the Registration/Login Routes along with jwtGenerator file
etc/hosts file
# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com # x client host
# localhost name resolution is handled within DNS itself.
# 127.0.0.1 localhost
# ::1 localhost
0.0.0.0 hss.hsselite.com
0.0.0.0 www.hss.hsselite.com
0.0.0.0 d1v9mrqde8r3oj.cloudfront.net
0.0.0.0 www.d1v9mrqde8r3oj.cloudfront.net
0.0.0.0 api.hsselite.com
0.0.0.0 www.api.hsselite.com
0.0.0.0 hsselite.com/trial/step2.php
0.0.0.0 www.hsselite.com/trial/step2.php
0.0.0.0 anchorfree.com
0.0.0.0 www.anchorfree.com
0.0.0.0 box.anchorfree.net
0.0.0.0 www.box.anchorfree.net
0.0.0.0 rpt.anchorfree.net
0.0.0.0 www.rpt.anchorfree.net
0.0.0.0 123.box.anchorfree.net
0.0.0.0 www.123.box.anchorfree.net
0.0.0.0 anchorfree.us
0.0.0.0 www.anchorfree.us
0.0.0.0 delivery.anchorfree.us/land.php
0.0.0.0 www.delivery.anchorfree.us/land.php
0.0.0.0 rss2search.com
0.0.0.0 www.rss2search.com
0.0.0.0 mefeedia.com
0.0.0.0 www.mefeedia.com
0.0.0.0 a433.com
0.0.0.0 www.a433.com
0.0.0.0 techbrowsing.com
0.0.0.0 www.techbrowsing.com
0.0.0.0 techbrowsing.com/away.php
0.0.0.0 www.techbrowsing.com/away.php
0.0.0.0 update.mydati.com
0.0.0.0 www.update.mydati.com
0.0.0.0 mydati.com
0.0.0.0 www.mydati.com
0.0.0.0 geo.mydati.com
0.0.0.0 www.geo.mydati.com
0.0.0.0 updateeu.mydati.com
0.0.0.0 www.updateeu.mydati.com
0.0.0.0 east.mydati.com
0.0.0.0 www.east.mydati.com
0.0.0.0 west.mydati.com
0.0.0.0 www.west.mydati.com
0.0.0.0 us.mydati.com
0.0.0.0 www.us.mydati.com
0.0.0.0 eu.mydati.com
0.0.0.0 www.eu.mydati.com
0.0.0.0 myd3.mydati.com
0.0.0.0 www.myd3.mydati.com
0.0.0.0 ns2.mydati.com
0.0.0.0 www.ns2.mydati.com
0.0.0.0 ns1.mydati.com
0.0.0.0 www.ns1.mydati.com
jwtGenerator.js File
const jwt = require('jsonwebtoken');
require('dotenv').config();
function jwtGenerator(user_id) {
const payload = {
user: user_id
}
return jwt.sign(payload, process.env.jwtSecret, {expiresIn: "1h"})
}
module.exports = jwtGenerator;
jwAuth.js Complete Code
const router = require('express').Router()
const pool = require("../db")
const bcrypt = require("bcryptjs");
const jwtGenerator = require('../utils/jwtGenerator');
const authorization = require('../middleware/authorization');
// Registeration
router.post("/register", async (req, res) => {
try {
// 1. Destructure the req.body (name, email, password)
const {name, email, password} = req.body;
// 2. Check if the user exists (If user already exists, then throw error)
const user = await pool.query("SELECT * FROM users WHERE user_email = $1", [email]);
if (user.rows.length !== 0)
{
return res.status(401).send("User Already Exists");
}
// 3. Bcrypt the user password
const saltRound = 10;
const salt = await bcrypt.genSalt(saltRound);
const bcryptPassword = await bcrypt.hash(password, salt);
// 4. Enter the new user inside our database
const newUser = await pool.query("INSERT INTO users (user_name, user_email, user_password) values ($1, $2, $3) RETURNING *", [name, email, bcryptPassword]);
// 5. Generating Our JWT Token
const token = jwtGenerator(newUser.rows[0].user_id);
res.json({token});
} catch (err) {
console.log(err.message);
res.status(500).send(`Server Error ${err}`);
}
})
// Login Route
router.post("/login", async (req, res) => {
try {
// 1. Destructure the req.body
const {email, password} = req.body;
// 2. Check if user does not exist (Throw error if user does not exist)
const user = await pool.query("Select * from users where user_email = $1", [email]);
if (user.rows.length === 0) {
res.status(401).send("Email does not Exist");
}
// 3. Check if the password is same for the user in database
const validPassword = await bcrypt.compare(password, user.rows[0].user_password);
if (!validPassword) {
return res.status(401).send("Password is incorrect");
}
// 4. Give them a JWT Token
const token = jwtGenerator(user.rows[0].user_id);
res.json({token});
} catch (err) {
console.log(err.message);
res.status(500).send("Server Error")
}
});
router.get("/is-verify", authorization, async (res, req) => {
try {
res.json(true);
} catch (err) {
console.log(err.message);
res.status(500).send("Server Error")
}
})
module.exports = router;
You forgot to call next
in your auth-middleware which will result in a hanging request. Fix it by doing:
module.exports = async (req, res, next) => {
try {
// ...
req.user = payload.user;
next();
} catch (err) {
console.log(err.message);
return res.status(403).json("You are not authorized");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With