GitHub OAuth (Passport)
The GitHub OAuth component provides a secure and standardized way to integrate GitHub authentication into your Servercn Express applications using the official passport, passport-github2.
It handles the complete OAuth 2.0 flow including authorization URL generation, token exchange, user information retrieval, and token refresh.
Features
- Complete OAuth 2.0 flow - Authorization, token exchange, and user info retrieval
- Secure by default - CSRF protection with state parameter
- Token management - Access token, refresh token, and ID token verification
- Express integration - Ready-to-use route handlers
- Type-safe - Full TypeScript support
- Flexible scopes - Customizable OAuth scopes
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
GitHub OAuth Setup
- Go to your GitHub Settings
- Developer settings -> OAuth Apps -> New OAuth App
- Fill in the required information
- Set Homepage URL to
http://localhost:9000(or your production URL) - Set Authorization callback URL to
http://localhost:9000/api/auth/github/callback(or your production URL) - Register application
- Generate a Client Secret
- Copy the Client ID and Client Secret
Environment Variables
Add the following to your .env file:
Ensure the following configuration are defined:
MVC: src/configs/env.ts
Feature: src/shared/configs/env.ts
Basic Implementation
1. MVC Structure
1. Configure passport in src/configs/passport.ts:
2. Create a GitHub OAuth controller in src/controllers/github-oauth.controller.ts or src/controllers/auth.controller.ts
3. Create a GitHub OAuth router in src/routes/github-oauth.routes.ts or src/routes/auth.routes.ts
4. Create a server in src/app.ts
2. Feature Structure
1. Configure passport in src/shared/configs/passport.ts:
2. Create a GitHub OAuth controller in src/modules/oauth/github-oauth.controller.ts or src/modules/auth/auth.controller.ts
3. Create a GitHub OAuth router in src/modules/oauth/github-oauth.routes.ts or src/modules/auth/auth.routes.ts
4. Create a index route in src/routes/index.ts
5. Create a server in src/app.ts
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 GitHub Developer Settings.
"bad_verification_code"
The code passed is incorrect or expired.
- The authorization code has expired (codes expire after 10 minutes)
- The code has already been used