How to Build an Authentication API with JWT Token in Node.js

Authentication Vs Authorization

Why JWT ?

Assuming that you’ve created node project. Install other dependency.

npm install mongoose express jsonwebtoken bcrypt - save

Encrypt Password

var encrypted = await bcrypt.hash(password, 10);

hash function Signature*

function hash(
data: string,
saltOrRounds: string | number
)

sign User

const token = jwt.sign(
{ user_id: user._id },
YOUR_TOKEN_SECRET
);

sign function Signature*

function sign(
payload: string | object,
secretOrPrivateKey: YOUR_TOKEN_SECRET,
options?: Object
)

Check User is Authorized

if(await bcrypt.compare(password, user.password))) return true;
return false;

Middleware for authentication

const verifyToken = (req, res, next) => {const token = req.headers["Authorization"];  if (!token) {
return res.status(403).send("Access Token Not Found");
}
try {
const decoded = jwt.verify(token, TOKEN_KEY);

} catch (err) {
return res.status(401).send("Token is not Valid");
}
return next();
};

* Just for your info

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store