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.
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.
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.
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.
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
PASSWORD in the
- Open the
.envfile and add these three variables.
TOKEN_KEY can be any random string. It is used by JWT.
- Open up a terminal and install the
controllersfolder and create
auth.controller.jsfile. Copy and paste the below code.
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
auth.routes.jsand register a new route for login.
- Lastly, in
server.js, use the registered route.
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.
- In the project root, create a folder called
middleware, and in that folder create the
auth.jsfile. Copy and paste the below code.
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.jsand modify the code like this.
That's it! Backend authentication is done 🎉.
It's time to implement front-end authentication.
- First, let's create a login page.
Login.cssfiles. Copy and paste the below code in
Login.jsxfile and use this in
This will render the login page.
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.jsfile and add this logic. If there is a token in
- Now in the
App.jsxfile, we need to send
tokenthrough the header, so that backend will verify it and gives access to the routes.
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 💯.
LEAVE A COMMENT OR START A DISCUSSION
5 min read
Hiring Angular Developers in 2023: Insider Tips & Strategies
Does your company struggle to create a modern, high-performance, cross-platform web app? Do you desire cost-effective development without compromising future software quality? Many web development teams utilize Angular to build complicated single-page apps. Hiring Angular programmers is difficult.
8 min read
How Feature Flags Can Help You Ship Faster and Smarter?
Are you tired of long development cycles and hesitant to push new features to production? Feature flags may be the solution you're looking for. In this blog post, we'll explore how feature flags can streamline your development process, reduce the risk of errors, and give you more control over the features you release to your users. From testing new features to rolling out changes to a select group of users, feature flags can help you do it all. Keep reading to learn how you can start using feature flags in your development workflow today.