How to add authorization in Node.js API

Authorization

Getting Started

Add Authentication

npm install bcryptjs jsonwebtoken
npm start

const bcrypt = require('bcryptjs');
let hashedPassword = bcrypt.hashSync(req.body.password, 10);
const user = await new User({
email: req.body.email,
password: hashedPassword,
username: req.body.username,
creation_date: moment().format("MMMM Do YYYY, h:mm:ss a")
})
if(bcrypt.compareSync(req.body.password, docs[0].password)){
res.status(200).json({ status: "success" })
}
else{
res.send("Invalid Credentials!");
}
if(bcrypt.compareSync(req.body.password, docs[0].password)){
let token = jwt.sign({ foo: 'bar' }, "f0af17449a83681de22db7ce16672f16f37131bec0022371d4ace5d1854301e0");
res.status(200).json({ status: "success", token: token })
}
else{
res.send("Invalid Credentials!");
}

Testing Registration API

Creating a Authorized User Route

const express = require("express");
const userController = require("../controllers/userController")
const userRouter = express.Router();

userRouter.route("/joke").get(userController.getJoke);

module.exports = userRouter;
const { Router: expressRouter } = require("express");
const router = expressRouter();

// auth routes
const authRouter = require("./authRoutes");
router.use("/auth", authRouter);

// user routes
const userRouter = require("./userRoutes");
router.use("/user", userRouter);

module.exports = router;

Adding Authorization

const jwt = require("jsonwebtoken")
const { jwt_key } = require("../config/db.config")
const { handleResponseWithStatus } = require("../helper/utils");



const verifyToken = (req, res, next)=>{
const token = req.headers.token
if(token!=undefined){
jwt.verify(token, jwt_key, function(err, decoded) {
if(err){
console.log(err)
res.send({ status: "error", error: 'Unauthorized User!' });
}
else{
if(decoded!=undefined){
console.log(decoded)
next();
}
else{
res.send({ status: "error", error: 'Unauthorized User!' });
}
}
});
}
else{
res.send({ status: "error", error: 'Unauthorized User!' });
}
}

module.exports = verifyToken;
module.exports = {
isAuthenticated: require("./verify"),
}
const express = require("express");
const userController = require("../controllers/userController")
const userRouter = express.Router();
const { isAuthenticated } = require("../middlewares");

userRouter.route("/joke").get(isAuthenticated, userController.getJoke);

module.exports = userRouter;

--

--

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
Musab Abbasi

Musab Abbasi

88 Followers

Computer Science Graduate with MERN stack website development expertise.