Authentication & Authorization in NodeJS
In this post, we will learn about how users can Authenticate or Authorize before making any requests to the server.
** Authentication: **
Authentication is a process of identifying if the user is claiming who they are.
** Authorization **
Authorization is determining if the user has the right permission to modify the content in the server.
Let's create a post request to register a user in the database.
const express = require('express');
const router = express.Router();
const {User} = require('../models/register');
const _ = require('lodash');
router.post('/', async(req, res) => {
let user = await User.findOne({email: req.body.email});
if(user) return res.status(500).send('user already exists')
user = new User(_.pick(req.body,['name','email','password']));
await user.save();
res.send(_.pick(user, ['_id','name','email']));
});
Above route is post request which takes email, password, username as parameters and store it in database.
We should not store plaintext of passwords in our database it's not a good practice.
So we need to hash the password and store it in our DB. To encrypt the password there is a module available in nodejs i.e. bcrypt.
Let's see how to encrypt a password using bcrypt module.
const bcrypt = require('bcrypt');
const express = require('express');
const router = express.Router();
const {User} = require('../models/register');
const _ = require('lodash');
router.post('/', async(req, res) => {
let user = await User.findOne({email: req.body.email});
if(user) return res.status(500).send('user already exists')
user = new User(_.pick(req.body, ['name','email','password']));
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(user.password, salt)
await user.save();
res.send(true);
});
Let's modify the response and send JWT token to the client.
Refer the below link to know more about JWT token
https://onecompiler.com/posts/3umnakrpa
const config = require('config');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const express = require('express');
const router = express.Router();
const {User} = require('../models/register');
const _ = require('lodash');
router.post('/', async(req, res) => {
let user = await User.findOne({email: req.body.email});
if(user) return res.status(500).send('user already exists')
user = new User(_.pick(req.body, ['name','email','password']));
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(user.password, salt)
await user.save();
const token = jwt.sign({_id: user._id, isAdmin: user.isAdmin}, config.get('jwtPrivateKey')); //this key should be stored in environment variables
res.header('x-auth-token',token).send(_.pick(user, ['_id','name','email']));
Once we sent the JWT token to the client should store the token and use this for future requests. So that we can say that the user is authorized to use the request/modify data.
At login time we need to validate the password whether password available in our DB or not
const isValid = await bcrypt.compare(‘1234’, hashed);