This module provides a simple implementation of Google OAuth 2.0 authentication in a Node.js application. It handles user authentication via Google, exchanges authorization codes for tokens, and retrieves user profile information.
- Redirect users to Google OAuth 2.0 for authentication.
- Handle the OAuth 2.0 callback and exchange authorization codes for access tokens.
- Retrieve authenticated user profile information...
Before setting up this module, ensure the following:
-
Google Cloud Project:
- Create a project on Google Cloud Console.
- Enable the "Google+ API" or "Google Identity Services" API.
- Generate OAuth 2.0 credentials (Client ID and Client Secret).
- Set the "Authorized redirect URI" to
http://localhost:<PORT>/auth/google/callback
(replace<PORT>
with your app's port).
-
Node.js:
- Ensure Node.js is installed (version 14.x or later recommended).
- Install
express
,axios
, anddotenv
npm packages.
-
Clone this repository or copy the module files into your project:
git clone <repository-url> cd google-auth-module
-
Install dependencies:
npm install
-
Create a
.env
file in the root of your project and add the following:PORT=3000 GOOGLE_CLIENT_ID=<Your-Google-Client-ID> GOOGLE_CLIENT_SECRET=<Your-Google-Client-Secret> GOOGLE_REDIRECT_URI=http://localhost:3000/auth/google/callback
-
Start the application:
node app.js
-
GET /auth/google
: Redirects the user to Google's OAuth 2.0 authentication page. -
GET /auth/google/callback
: Handles the callback from Google and retrieves the user's profile information.
- Navigate to
http://localhost:3000/auth/google
. - You will be redirected to Google's login page.
- After logging in, Google redirects back to
http://localhost:3000/auth/google/callback
. - The application exchanges the authorization code for tokens and fetches the user's profile information.
On successful authentication, the API responds with:
{
"message": "Authentication successful",
"user": {
"id": "1234567890",
"email": "[email protected]",
"name": "John Doe",
"picture": "https://example.com/photo.jpg"
}
}
-
Change Scopes: Update the
scope
parameter in thegetGoogleAuthUrl
function to request additional permissions:scope: 'email profile https://www.googleapis.com/auth/calendar',
-
Port Configuration: Modify the
PORT
value in the.env
file to run the application on a different port.
-
If the authorization code is missing, the API responds with:
{ "error": "Authorization code not found" }
-
For token exchange or profile retrieval failures, the API responds with:
{ "error": "Authentication failed" }
Check the server logs for detailed error information.
This project is licensed under the MIT License. See the LICENSE file for details.
Contributions are welcome! Please fork the repository and submit a pull request.
For issues or feature requests, please open an issue in the repository or contact the maintainer.