This is a simple Express application that uses Google OAuth 2.0 for authentication via Passport.js. It allows users to log in with their Google account, view a personalized profile page, and log out.
- Google OAuth 2.0 authentication with Passport.js
- Session-based authentication
- Displays a personalized greeting on the profile page
- Simple login and logout functionality
To run this project, you'll need:
- Node.js (version 12 or higher)
- A Google Cloud project with OAuth credentials
- A
.env
file to securely manage sensitive information
- Go to the Google Cloud Console.
- Create a new project or select an existing one.
- Go to Credentials in the APIs & Services section.
- Click Create Credentials and select OAuth 2.0 Client IDs.
- Configure the consent screen and add
http://localhost:3000/auth/google/callback
as the redirect URI. - Note your Client ID and Client Secret – you’ll need them in the
.env
file.
git clone https://github.com/sahil352005/google-oauth-2.0.git
cd google-oauth-2.0
Run the following command to install the necessary dependencies:
npm install
Create a .env
file in the root directory of the project and add your Google OAuth credentials:
GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret
Start the server with the following command:
npm start
The server should now be running at http://localhost:3000
.
/
- Home page with a "Login with Google" link./auth/google
- Initiates Google authentication./auth/google/callback
- Callback URL after Google authentication./profile
- Displays the user’s Google display name (only accessible when logged in)./logout
- Logs the user out and redirects to the home page.
- When you navigate to the home page, click the "Login with Google" link.
- Google will ask for your permission to share your profile information.
- After granting permission, you’ll be redirected to the
/profile
page, where you’ll see a welcome message with your Google display name. - Use the
/logout
route to end the session and return to the home page.
- Make sure the Google Client ID and Client Secret in the
.env
file are correct. - Ensure that http://localhost:3000/auth/google/callback is added as an authorized redirect URI in your Google Cloud project.
- If you encounter an issue with
req.logout()
, ensure that you’re using Passport version compatible with the session handling method used.
This project is open-source and available under the MIT License.
This README provides all essential information for users to understand and set up Google OAuth in this application.