DEV Community

Cover image for Adding Authentication to full stack MERN web application
Rakesh Potnuru
Rakesh Potnuru

Posted on • Edited on • Originally published at blog.itsrakesh.co

Adding Authentication to full stack MERN web application

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

⚠️ Warning: Authentication used in this tutorial is not secure. I don't recommend using this authentication method for real projects.

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  • 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,
};
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode
  • Lastly, in server.js, use the registered route.
...
const AuthRouter = require("./routes/auth.route");
...

...
app.use("/api/auth", AuthRouter);
...
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  • 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;
Enter fullscreen mode Exit fullscreen mode

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);
...
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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>
);
...
Enter fullscreen mode Exit fullscreen mode
  • 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();
};
...
Enter fullscreen mode Exit fullscreen mode

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 😍.


Follow for more πŸ’―.

Top comments (0)