Implementing Authentication in NodeJS App using OAuth2.0

Tasadduq Ali
3 min readJul 9, 2023

Implementing OAuth 2.0 Authentication in Node.js

Step 1: Set Up the Node.js Project

Start by setting up a new Node.js project using a package manager like npm or yarn. Run the following command in your terminal:

csharpCopy code
npm init

This will create a package.json file to manage your project's dependencies.

Step 2: Install Required Packages

To implement OAuth 2.0 authentication in Node.js, we need to install the necessary packages. Run the following command in your terminal:

Copy code
npm install express passport passport-google-oauth20

This will install Express.js, a popular Node.js web framework, and the passport and passport-google-oauth20 packages, which are essential for OAuth 2.0 authentication with Google.

Step 3: Create OAuth 2.0 Credentials

Before proceeding, you need to create OAuth 2.0 credentials in the respective platform's developer console. For example, if you want to implement Google OAuth, go to the Google Developers Console (**https://console.developers.google.com/**), create a new project, and enable the Google OAuth 2.0 API. Obtain the client ID and client secret for your application.

Step 4: Configure Passport.js

Create a new file, passport.js, to configure Passport.js, a popular authentication middleware for Node.js. In this file, initialize Passport.js, set up the Google OAuth 2.0 strategy, and define serialization and deserialization functions.

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

passport.use(
new GoogleStrategy(
{
clientID: 'YOUR_CLIENT_ID',
clientSecret: 'YOUR_CLIENT_SECRET',
callbackURL: '/auth/google/callback',
},
(accessToken, refreshToken, profile, done) => {
// Code to handle user authentication and retrieval
}
)
);

passport.serializeUser((user, done) => {
// Code to serialize user data
});

passport.deserializeUser((id, done) => {
// Code to deserialize user data
});

Replace 'YOUR_CLIENT_ID' and 'YOUR_CLIENT_SECRET' with your own credentials obtained from the OAuth provider.

Step 5: Create Authentication Routes

Create a new file, authRoutes.js, to define the authentication routes for your application. In this file, define the routes for initiating the OAuth 2.0 authentication flow, handling the callback URL, and logging out the user.

javascriptCopy code
const express = require('express');
const passport = require('passport');
const router = express.Router();

// Initiates the Google OAuth 2.0 authentication flow
router.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));

// Callback URL for handling the OAuth 2.0 response
router.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), (req, res) => {
// Successful authentication, redirect or handle the user as desired
res.redirect('/');
});

// Logout route
router.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
});

module.exports = router;

Step 6: Set Up Express.js Server

In your main server file (e.g., app.js), import the required packages and configure the Express.js server. Include the Passport.js middleware, session management, and authentication routes.

javascriptCopy code
const express = require('express');
const session = require('express-session');
const passport = require('passport');
const authRoutes = require('./authRoutes');

const app = express();

app.use(session({ secret: 'YOUR_SESSION_SECRET', resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());

app.use('/', authRoutes);

// Start the server
app.listen(3000, () => {
console.log('Server started on port 3000');
});

Replace 'YOUR_SESSION_SECRET' with a secret string used to sign the session ID cookie.

Step 7: Testing the Authentication Flow

Start your Node.js server using node app.js or the appropriate command. Visit the appropriate route (e.g., /auth/google) in your web browser to initiate the OAuth 2.0 authentication flow. After successful authentication, you will be redirected to the callback URL (/auth/google/callback) with the user information. You can then handle this information as desired, such as storing it in a database or creating a user session.

if you have any questions or suggestions just do let me know on my Instagram or at codeculturepro@gmail.com

--

--

Tasadduq Ali

I am MERN Stack developer working in UAE Govt to digitize their massive services. I will help you to become highly skilled Coder 😉