Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Implementing Google OAuth2 Authentication in Node.js project using passport: A Step-by-Step Guide

Sign upSign InSign upSign InChiboyFollowBits and Pieces--ListenShareIn this tutorial, we will explore the process of implementing Gmail Authentication in a Node.js application. Gmail authentication allows users to log into your application using their Gmail accounts. By leveraging Gmail’s OAuth2 protocol, we can securely authenticate users and grant them access to our application. Let’s dive into the step-by-step process of setting up Gmail authentication on the backend.Before we begin, we need to install the necessary dependencies and configure environment variables. We will be using packages such as Passport.js and the Google OAuth2 strategy to handle the authentication process. Additionally, we need to obtain the required credentials from the Google API Console and set them as environment variables to secure our application.NOTE: This tutorial is based on implementation of Gmail authentication on the backendWithout wasting much time let's dive into building. Follow the steps below:Go to Google API console > Create a new project > On the left side bar click on credentials > Click on the “Create Credentials” button and choose “OAuth client ID” > Select “Web application” as the application type > Enter a name for your OAuth client ID > In the “Authorized JavaScript origins” field, enter the URL of your application’s server (e.g., “http://localhost:5000" if you are running it locally) > In the “Authorized redirect URIs” field, enter the callback URL for the authentication flow (e.g., “http://localhost:5000/auth/google/callback") > Click the “Create” button to create your OAuth client ID > You will now see your newly created OAuth client ID. Note down the “Client ID” and “Client Secret” values as these will be used in your application.2. Now that we have obtained our credentials from Google developer console, let's create our project. Open cmd or gitbash terminal then copy and paste the command to create a new project/folder.3. Initialize a new Node.js project and follow the prompts to set it up:4. Install the required modules for this application using the following command:5. Now let's create a file in the root directory and name it passport.js, then add this code to itThis above code snippet demonstrates the implementation of Google Oauth 2.0 authentication using Passport.js.i. passport.use(new GoogleStrategy({…}) : This configures Passport to use the Google OAuth 2.0 authentication strategy. ii. function(request, accessToken, refreshToken, profile, done) { … }: This is the callback function that gets executed when a user is successfully authenticated.iii. passport.serializeUser(function(user, done) { … }): This function is used to serialize the user object into a session. In this case, the entire user object is serialized. The serialized user object is then stored in the session.iv. passport.deserializeUser(function(user, done) { … }): This function is used to deserialize the user object from the session. It retrieves the serialized user object from the session and passes it to the done callback.💡 You can now encapsulate this passport logic into its own component which you can test, document, and version independently and then share across multiple projects using Bit, with a simple bit import your.username/passport command.bit.dev6. We have successfully created our Google strategy configuration in the above passport.js file. Next, we need to create our server.js file which is the entry point to our application. Then copy and paste the code below to the server.jsHere is the breakdown of the server.js:i. Firstly, we imported the required dependencies (dotenv, express, passport, express-session) and also the passport.js for the authentication configuration. ii. The express-session middleware is meant to provide secret, disabling resaving sessions and preventing uninitialized sessions from being saved.iii. Next, we then initialize passport middleware and use it in the Express application.iv. The isLoggedIn middleware is defined to check if the user is authenticated. If not, it sends a 401 status code.v. The “/google” route is defined for initiating the Google OAuth consent screen. It uses the passport.authenticate middleware with the "google" strategy and specifies the desired scope.vi. The “/google/callback” route is defined as the callback URL for Google Oauth Authentication. It uses the passport.authenticate middleware to handle the authentication process and redirects to "/success" if successful, or "/failed" if not.vii. The “/logout” route is defined to log out the authenticated user. It destroys the session and calls req.logout() with a callback to log a message and redirect to "/home".NOTE: To start this application on the Node server, open your terminal and navigate to the root directory of the project. Then, run the following command:This command will start the Node server, and your application will be running on port 5000. Once the server is running, you can open your web browser and visit http://localhost:5000/google to access the Google authentication screen.In conclusion, by following these steps, you should now have a good understanding of how to authenticate with Google OAuth2 using Passport and how Express Session works for storing cookies on the client-side. You can find the source code for this project available for your reference and usage.Feel free to explore the code and customize it according to your requirements. Happy coding!Bit’s open-source tool help 250,000+ devs to build apps with components.Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.→ Learn moreSplit apps into components to make app development easier, and enjoy the best experience for the workflows you want:blog.bitsrc.ioblog.bitsrc.ioblog.bitsrc.iobit.devblog.bitsrc.iobit.devitnext.ioblog.bitsrc.io----Bits and PiecesHalf Human, Half AmazingChiboyinBits and Pieces--2Fernando DoglioinBits and Pieces--Daniel GlejznerinBits and Pieces--8ChiboyinBits and Pieces--Hamza Makhkhas--Sadeem Sattar--1Love SharmainDev Genius--23king AjinStackAnatomy--Anto SemeraroinBits and Pieces--1Lorenzo ZarantonelloinLevel Up Coding--2HelpStatusWritersBlogCareersPrivacyTermsAboutText to speechTeams



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

Implementing Google OAuth2 Authentication in Node.js project using passport: A Step-by-Step Guide

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×