What Is Authorization?🤔🤔🤔
Authorization is a security mechanism used to determine user/client privileges or access levels related to system resources, including computer programs, files, services, data, and application features. Authorization is normally preceded by authentication for user identity verification. Or
Authorization is simply a process of granting or denying access to resources. Which comes after Authentication
So What’s Authentication
In simple terms, it’s the process of verifying the identity of a user.
Then Authorization gives you access to pages either as a user or an admin.
How Do I Do This On Node.js?😣😣
No need to worry it’s quite simple
The package popularly used for Authorization is the JSONWEBTOKEN (JWT)
JSONWEBTOKEN(JWT)
JSON Web Token is a proposed Internet standard for creating data with optional signature and/or optional encryption whose payload holds JSON that asserts some number of claims. The tokens are signed either using a private secret or a public/private key.
This means that JWT produces a token for you as a user or admin when you are authenticated. Now, a SECRET key will be compared to your generated token every time you attempt to access a route. You won’t be granted access to this page if this doesn’t match or the token is invalid.
I used the BEARER token for my project but we also have the OAuth2.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYzMGE3MjQxNGE3MzFjZWY2MTE3NGY4MyIsImlhdCI6MTY2MTYyOTA5NiwiZXhwIjoxNjYxNzE1NDk2fQ.QYFUATkHwoXCO7x8-588KjLGnfy6OgG740OScGxCz6o => This is what a bearer token looks like.
exports.isAuth = async (req, res, next) => {
try {
const token = req.headers.authorization.split(' ')[1];
if (!token) {
return res.status(401).json({ message: 'Token Is missing' });
}
const decoded = await jwt.verify(token, process.env.SECRET_KEY);
if (!decoded) {
throw new Error();
}
req.user = decoded;
next();
} catch (e) {
return res.status(401).json({ message: 'Token expired' });
}
};
This is an example of how your Authorization file will look
Now you import the block of codes in your routes
const express = require("express");
const { addHouse } = require("../controllers/house.controller");
const { isAuth } = require("../middleware/isAuth");
const router = express.Router();
router.post("/create", isAuth, addHouse);
module.exports = router;
`