Horje
Authentication and Authorization with OAuth in MERN

In this digital era, all people want to create a website for their business, education or any other purpose. Making it secure and protected from various vulnerabilities like attacks, threads, viruses and hackers. In your application, there must be a layer of security that can prevent those security issues. When you build an application using the MERN stack you will come across an OAuth which can increase your security. This article will help you to prevent those attacks and help your site to verify your traffic. You will also get to know about authentication and authorization in this article which will help you to identify each term.

What is Authentication and Authorization?

Authentication

It is the process of verifying the identity of a user. This involves the checking of user passwords and their respective username. Once the username and password is authenticated from the database your user will be redirected to the dashboard. This is the simple step in which we just check the username and password given by your user.

Authorization

In this different-different user have their respective permission and they are allowed to do that only. This will ensure that your normal user can not update your database. The permission or privilege is given by the admin of your application.

Introduction to OAuth

OAuth is a widely used authorization framework that allows third-party services to exchange information without giving user credentials. OAuth provides a secure way to authenticate users and authorize access to resources. This is also known as Open Authorization or OAuth.

OAuth Flow

  • User Authentication: The user authenticates with an OAuth provider like Google, Facebook, GitHub, etc.
  • Authorization Grant: The provider grants an authorization code to the application.
  • Token Exchange: The application exchanges the authorization code for an access token.
  • Access Resources: The application uses the access token to access protected resources on behalf of the user.

Implementing OAuth in MERN

Setting Up the MERN Stack

Before going into the OAuth implementation, Let’s ensure that you have a basic MERN stack setup.

  • MongoDB: A NoSQL database for storing user data.
  • Express: A web framework for Node.js.
  • React: A front-end library for building user interfaces.
  • Node.js: A JavaScript runtime for server-side code.

Step-by-Step Implementation

Install Necessary Packages

Step 1: First, install the necessary npm packages for implementing OAuth. This includes passport, passport-oauth, and the specific strategy for the OAuth provider you choose (e.g., passport-google-oauth20 for Google).

npm install passport passport-oauth2 passport-google-oauth20
Step-01

Step 1

Also install the express and express-session by the following command

npm install express express-session
Step-02

Step 02

Configure Passport

Step 2: In your Express server, configure Passport to use the OAuth strategy. Create a file named passport-config.js and set up the strategy:

JavaScript
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;

passport.use(new GoogleStrategy({
  clientID: process.env.GOOGLE_CLIENT_ID,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET,
  callbackURL: "/auth/google/callback"
},
  function (accessToken, refreshToken, profile, done) {
    // Here, you would typically find or create a user in your database
    User.findOrCreate({ googleId: profile.id }, function (err, user) {
      return done(err, user);
    });
  }
));

passport.serializeUser((user, done) => {
  done(null, user.id);
});

passport.deserializeUser((id, done) => {
  User.findById(id, (err, user) => {
    done(err, user);
  });
});

Set Up Routes for Authentication

Step 3: Create routes to handle authentication requests. In your server.js or app.js:

JavaScript
const express = require('express');
const passport = require('passport');
const app = express();

app.get('/auth/google',
  passport.authenticate('google', { scope: ['profile', 'email'] })
);

app.get('/auth/google/callback', 
  passport.authenticate('google', { failureRedirect: '/' }),
  (req, res) => {
    // Successful authentication, redirect home.
    res.redirect('/');
  }
);

Protect Routes Using Middleware

Step 4: To protect routes and ensure only authenticated users can access them, create a middleware function:

JavaScript
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }
  res.redirect('/login');
}

Use this middleware to protect routes:

JavaScript
app.get('/profile', ensureAuthenticated, (req, res) => {
  res.send('This is your profile page.');
});

Step 5: Now install nodemon in you Node application. This will help you automatically restart your server whenever you save your file.

npm install -g nodemon
Step-03

Step 3

Step 6: Start your server.

nodemon server.js

Frontend Integration with React

Step 1: Create your react application by using the following command in you IDE.

npx create-react-app frontend
Create-Frontend-01

Create Frontend 01

Step 2: Install axios in your react application to send api calls.

npm install axios

Step 3: Copy the following code and paste this in your App.js and App.css file.

JavaScript
// src/App.js
import React from 'react';
import './App.css';

function App() {
  const loginWithGoogle = () => {
    window.location.href = 'http://localhost:5000/auth/google';
  };

  return (
    <div className="App">
      <header className="App-header">
        <h1>Welcome to My App</h1>
        <button onClick={loginWithGoogle}>Login with Google</button>
      </header>
    </div>
  );
}

export default App;
CSS
/* src/App.css */
.App {
  text-align: center;
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

button {
  background-color: #61dafb;
  border: none;
  padding: 1em;
  font-size: 1em;
  cursor: pointer;
  margin-top: 20px;
  border-radius: 5px;
}

button:hover {
  background-color: #21a1f1;
}

Conclusion

Implementing authentication and authorization with OAuth in a MERN stack application enhances security and improves user experience. This will provide you the steps to secure your application from the unauthorized access. By following the steps in this article, you can integrate OAuth into your MERN stack application, providing secure access to your users. This setup ensures that user data is protected, and users can easily authenticate using their existing accounts from providers like Google, Facebook, or GitHub.

Authentication and Authorization with OAuth in MERN – FAQs

What is OAuth and why use it in a MERN stack application?

” OAuth is a secure authorization standard allowing users to grant third-party access without sharing credentials. It enhances security, improves user experience with single-click logins, and integrates easily with services like Google and Facebook. ”

How do I handle user sessions after OAuth authentication in MERN?

” Use express-session to manage sessions, configure Passport to serialize/deserialize users, and protect routes with middleware to ensure only authenticated users can access them. “

What to do if my server exits automatically after starting?

” Check for syntax errors, use nodemon for better error logging, ensure all environment variables are set correctly, and verify package.json scripts for correct start and dev commands. “




Reffered: https://www.geeksforgeeks.org


TechTips

Related
How to Download YouTube Videos using yt-dlp? How to Download YouTube Videos using yt-dlp?
How to Open MBOX File in XPS? How to Open MBOX File in XPS?
How to Turn Off Cellular Data for Specific Apps on Android? How to Turn Off Cellular Data for Specific Apps on Android?
How to Use Windows Security in Windows 11? How to Use Windows Security in Windows 11?
Best YouTube to AAC Converter Best YouTube to AAC Converter

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
20