This application demonstrates how Google OAuth 2.0 authentication works with Node.js.
- Authentication with Google OAuth 2.0
- Display of user profile information after authentication
- Session management
- Visual explanation of the OAuth flow
- Node.js and npm installed
- A Google Cloud Platform account
- A registered Google OAuth application
- Clone this repository
- Install dependencies:
npm install - Create a
.envfile in the root directory (use.env.exampleas a template):PORT=3000 GOOGLE_CLIENT_ID=your_google_client_id GOOGLE_CLIENT_SECRET=your_google_client_secret CALLBACK_URL=http://127.0.0.1:3000/auth/google/callback SESSION_SECRET=some_random_secret_key
- Go to the Google Cloud Console
- Create a new project (or select an existing one)
- Navigate to "APIs & Services" > "Credentials"
- Click "Create Credentials" > "OAuth client ID"
- Select "Web application" as the application type
- Add a name for your OAuth client
- Under "Authorized JavaScript origins", add:
http://127.0.0.1:3000 - Under "Authorized redirect URIs", add:
http://127.0.0.1:3000/auth/google/callback - Click "Create"
- Copy the generated Client ID and Client Secret to your
.envfile
Start the development server:
npm run dev
Or for production:
npm start
Navigate to http://127.0.0.1:3000 in your browser to use the application.
-
User Clicks "Login with Google"
- The app redirects to
/auth/google - Passport.js initiates the OAuth flow
- The app redirects to
-
User Is Redirected to Google's Authentication Page
- Google asks for permission to share profile information with our app
-
Google Redirects Back with Authorization Code
- After successful authentication, Google redirects to our callback URL with a temporary code
-
Server Exchanges Code for Access Tokens
- Our server uses the code, client ID, and client secret to obtain access tokens from Google
-
Server Uses Tokens to Fetch User Profile
- The access token is used to request the user's profile information from Google's API
-
User is Authenticated in Our App
- User profile is stored in the session
- User is redirected to the profile page
index.js- Main server file with Express and Passport configurationviews/- EJS templates for the application UIhome.ejs- Home page with login buttonprofile.ejs- Profile page showing user information
.env- Environment variables (not committed to git).env.example- Example environment variables