paint-brush
How to Add Authentication to a Full Stack MERN Web Applicationby@itsrakesh
6,725 reads
6,725 reads

How to Add Authentication to a Full Stack MERN Web Application

by Rakesh PotnuruNovember 8th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

This article is part 2 of [Let's build and deploy a full stack MERN web application] In this tutorial, let's see the problem and how to tackle it. To prevent unauthorized access to your app, add authentication. The problem is that anyone can use it and add activities to your database. We'll build basic authentication without the use of any libraries. We need to implement backend authentication and authorize some routes. We'll implement **login authentication** with JWT. JWT is used is to verify that the user has permission to perform an action.

Company Mentioned

Mention Thumbnail
featured image - How to Add Authentication to a Full Stack MERN Web Application
Rakesh Potnuru HackerNoon profile picture

This article is part 2 of "Let's build and deploy a full stack MERN web application". In that tutorial, we created an application called Productivity Tracker that allows you to log your daily activities. However, there is a problem with our app. Can you figure it out 👀? Your hint is in the title of this article. In this tutorial, let's see the problem and how to tackle it.

Let's get started

The Problem

Since your application is currently available online, anyone can use it and add activities to your database. That is not good, is it? Here, authentication steps in to save the day. To prevent unauthorized access to your app, add authentication.

authenticate

Adding Authentication

We had to develop front-end and back-end authentication separately because we separated the two. Once more, for the sake of simplicity, we'll build basic authentication without the use of any libraries.

Backend authentication

We need to implement backend authentication and authorize some routes.

Authentication vs Authorization

These two words can be confusing to you. Authentication is allowing someone with credentials to access our application and Authorization is giving access to resources to authorized people.

authentication vs authorization

In our scenario, authorization grants access to resources like creating activities and fetching activities whereas authentication entails logging into the application.

Introduction to JWT

JSON Web Token (JWT) is a compact URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.


In simple terms, JWT is used is to verify that the user has permission to perform an action.

Let's implement login authentication with JWT.


Since you are the only person using your application you don't need a signup functionality and you can store EMAIL and PASSWORD in the .env file.


  • Open the .env file and add these three variables.
TOKEN_KEY=somesecrettoken
EMAIL=youremail
PASSWORD=yourpassword

Here TOKEN_KEY can be any random string. It is used by JWT.

  • Open up a terminal and install the jsonwebtoken package.
npm i jsonwebtoken
  • Open controllers folder and create auth.controller.js file. Copy and paste the below code.
const jwt = require("jsonwebtoken");

require("dotenv").config();

const EMAIL = process.env.EMAIL;
const PASSWORD = process.env.PASSWORD;

/* If the email and password are correct, then return a token. */
const login = (req, res) => {
  /* Destructuring the email and password from the request body. */
  const { email, password } = req.body;

  if (email === EMAIL && password === PASSWORD) {
    /* Creating a token. */
    const token = jwt.sign({ email }, process.env.TOKEN_KEY, {
      expiresIn: "2h",
    });
    return res.status(200).json({
      statusCode: 200,
      msg: "Login successful",
      token,
    });
  }
  return res.status(401).json({
    statusCode: 401,
    msg: "Invalid Credentials",
  });
};

module.exports = {
  login,
};

The code above checks to see if the email address and password match, and if they do, it generates a token and sends it to the front end to implement front-end authentication.

  • Open the routes folder create auth.routes.js and register a new route for login.
const express = require("express");

const { login } = require("../controllers/auth.controller");

const router = express.Router();

router.post("/login", login);

module.exports = router;
  • Lastly, in server.js, use the registered route.
...
const AuthRouter = require("./routes/auth.route");
...

...
app.use("/api/auth", AuthRouter);
...

We successfully implemented authentication. Now only authenticated people can access our application. But authenticated people can still access our resources and add activities because we haven't authorized those routes.

Let's create a middleware to authorize these routes.

GET /api/activities

POST /api/activity
  • In the project root, create a folder called middleware, and in that folder create the auth.js file. Copy and paste the below code.
const jwt = require("jsonwebtoken");

require("dotenv").config();

/* It checks if the token is valid and if it is, it decodes it and attaches the decoded token to the request object */
const verifyToken = (req, res, next) => {
  const token = String(req.headers.authorization)
    .replace(/^bearer|^jwt/i, "")
    .replace(/^\s+|\s+$/gi, "");

  try {
    if (!token) {
      return res.status(403).json({
        statusCode: 403,
        msg: "A token is required for authentication",
      });
    }
    /* Verifying the token. */
    const decoded = jwt.verify(token, process.env.TOKEN_KEY);
    req.userData = decoded;
  } catch (err) {
    return res.status(401).json({
      statusCode: 401,
      msg: "Invalid Token",
    });
  }
  return next();
};

module.exports = verifyToken;

We created a middleware function called verifyToken() to verify the token sent by the front end through the header. If verification is successful then the user can access the above routes.

  • Now open activity.route.js and modify the code like this.
...
router.get("/activities", auth, getActivities);

router.post("/activity", auth, addActivity);
...

That's it! Backend authentication is done 🎉.

Frontend authentication

It's time to implement front-end authentication.

  • First, let's create a login page.
  • In src folder create Login.jsx and Login.css files. Copy and paste the below code in Login.jsx file and use this in Login.css.
import React from "react";

import "./Login.css";

const Login = () => {
  /* When the user submits the form, prevent the default action, grab the email and password from the form, send a POST request to the backend with the email and password, and if the response is successful, store the token in local storage and reload the page. */
  const handleSubmit = async (event) => {
    event.preventDefault();
    const { email, password } = event.target;

    const response = await fetch(
      `${process.env.REACT_APP_BACKEND_URL}/auth/login`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          email: email.value,
          password: password.value,
        }),
      }
    );

    const data = await response.json();
    localStorage.setItem("token", data.token);
    window.location.reload();
  };

  return (
    <div className="login">
      <h1>Login</h1>
      <form onSubmit={handleSubmit}>
        <span>
          <label htmlFor="email">Email:</label>
          <input type="email" id="email" name="email" />
        </span>
        <span>
          <label htmlFor="password">Password:</label>
          <input type="password" id="password" name="password" />
        </span>
        <button type="submit">Login</button>
      </form>
    </div>
  );
};

export default Login;

This will render the login page.

login page

The handleSubmit() gets the email and password from the form, makes a POST request, and sends email and password values for verification. After that server verifies and sends back a token that we can use to access resources.

Here we are using localStorage to store the value in the browser permanently so that we won't get logged out after closing the application or browser.

  • Open the index.js file and add this logic. If there is a token in localStorage render App.jsx otherwise Login.jsx.
...
const token = localStorage?.getItem("token");

root.render(
    <React.StrictMode>
    {token ? <App /> : <Login />}
    </React.StrictMode>
);
...
  • Now in the App.jsx file, we need to send token through the header, so that backend will verify it and gives access to the routes.
...
useEffect(() => {
    const fetchData = async () => {
      const result = await fetch(
        `${process.env.REACT_APP_BACKEND_URL}/activities`,
        {
          headers: {
            Authorization: `Bearer ${token}`, // <----------- HERE
          },
        }
      );
      const data = await result.json();
      setActivities(data);
    };
    fetchData();
}, [token]);
...

...
const addActivity = async (event) => {
    event.preventDefault();

    const newActivity = {
      name: event.target.activity.value,
      time: event.target.time.value,
    };

    await fetch(`${process.env.REACT_APP_BACKEND_URL}/activity`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`, // <---------- HERE
      },
      body: JSON.stringify(newActivity),
    });

    event.target.activity.value = "";
    event.target.time.value = "";
    window.location.reload();
};
...

Done ✅! We implemented both frontend and backend authentication. Now only you can access your application 🥳 (as long as you don't share your credentials 👀).

Source code: productivity-app


In the next article, we will learn how to write tests for frontend and backend 😍.


Also Here