DEV Community

Cover image for User Authentication -JsonWebTokens (MERN Stack)
Reshma Shaik
Reshma Shaik

Posted on โ€ข Edited on

2 1 2 1 2

User Authentication -JsonWebTokens (MERN Stack)

Let's learn and develop along.!๐Ÿ˜Š

Part4
  • If anyone missed the previous part you can vist from here checkout๐Ÿ‘ˆ

  • Let me tell you the process of using jsonwebtokens.

Process:

  • we require them after installing the jsonwebtoken dependency to our initial project.

npm i jsonwebtoken

  • we also install bcrypt along with it, inorder to hash our passwords with this package.

npm i bcrypt

  • after adding required route handlers,and the models to server component.

  • inside the route handlers(i.e. controllers) create an token object to get the jwt for the specified user id whenever he/she logins.

    const token = jwt.sign({ _id: user._id }, process.env.JWT_SECRET, { expiresIn: "1h" });
Enter fullscreen mode Exit fullscreen mode
  • then sends the token as a response body to the client
    res.header('auth-token', token).send(token);

  • and this new token generation is formed everytime the user logins.

  • this authentication helps to access the protected routes of particular users who has access to particualar routes after login.

  • like after logging in to instagram account user can access posts section.

  • for this verifyToken function helps to access as we pass that func as a param to the posts route

const express = require('express');
const verifyToken = require('../utils/verifyToken');

const router = express.Router();

router.get('/', verifyToken, (req, res) => {
    res.send('This is a protected post');
});

module.exports = router;
Enter fullscreen mode Exit fullscreen mode
  • this verifyToken method requires the respective module and performs the verification process like this
const jwt = require('jsonwebtoken');

module.exports = function(req, res, next) {
    const token = req.header('auth-token');
    if (!token) return res.status(401).send('Access denied');

    try {
        const verified = jwt.verify(token, process.env.JWT_SECRET);
        req.user = verified;
        next();//calls the next middleware function
    } catch (err) {
        res.status(400).send('Invalid token');
    }
};
Enter fullscreen mode Exit fullscreen mode

from above we define the object token that is fetched from the request header.

if token is not present we get response "access denied." and not redirect to posts page.

and if we found the token valid, it will return the decoded payload(usually has user's id and details), ans allows to the protected route that is posts page.

  • To test this all ,you can use an extension called Thunder Client inorder to see server side checks, if you didn't set up frontend.

It is usual to say that ,start working on backend first to set things up and understand it's working fine.If ur good to go then go on implementing the frontend based on the schema reference.
Which should match ultimately.

For any further queries or discussions reach mme out in comment section.Consider this as a review or quick revision post.

Happy Developing!

tq

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, weโ€™ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, weโ€™ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay