Google OAuth (Passport)
The Google OAuth component provides a secure and standardized way to integrate Google authentication into your Servercn Express applications using the official passport, passport-google-oauth20.
Installation Guide
npx servercn-cli add oauthYou will be prompted to select a file upload provider:
The CLI will then automatically configure the component based on your selected provider.
Prerequisites
Google Cloud Console Setup
- Go to the Google Cloud Console
- Create a new project or select an existing one
- Enable the Google+ API (or Google Identity API)
- Go to Credentials → Create Credentials → OAuth client ID
- Configure the OAuth consent screen:
- Choose External (for testing) or Internal (for Google Workspace)
- Fill in the required information
- Create OAuth 2.0 Client ID:
- Application type: Web application
- Authorized JavaScript origins: Add your origin URL (e.g.,
http://localhost:9000) - Authorized redirect URIs: Add your callback URL (e.g.,
http://localhost:9000/api/auth/google/callback)
- Copy the Client ID and Client Secret
Environment Variables
Add the following to your .env file:
Ensure the following configuration are defined:
Basic Implementation
1. Configure Passport Strategy
2. Create a Google OAuth Controller
3. Create a Google OAuth Router
4. Initialize passport
Success Response
This response is formated by ApiResponse component.
Common Issues
"redirect_uri_mismatch"
Ensure your redirect URI in .env exactly matches the one configured in Google Cloud Console.
"invalid_grant"
This usually means:
- The authorization code has expired (codes expire after a few minutes)
- The code has already been used
- The redirect URI doesn't match
"access_denied"
The user denied permission. Handle this gracefully in your UI.