Skip to content

Latest commit

 

History

History
187 lines (143 loc) · 5.09 KB

File metadata and controls

187 lines (143 loc) · 5.09 KB

Google OAuth Setup Guide

🚀 Quick Setup Steps

1. Get Google OAuth Credentials

  1. Go to Google Cloud Console
  2. Create a new project or select an existing one
  3. Navigate to APIs & Services > Credentials
  4. Click Create Credentials > OAuth 2.0 Client ID
  5. Configure the OAuth consent screen if prompted:
    • User Type: External (for testing)
    • Add your email as a test user
  6. For Application type, select Web application
  7. Add Authorized redirect URIs:
    • http://localhost:5000/api/auth/google/callback (for development)
    • https://yourdomain.com/api/auth/google/callback (for production)
  8. Click Create and copy your:
    • Client ID
    • Client Secret

2. Update Environment Variables

Add these to your .env file:

GOOGLE_CLIENT_ID=your_google_client_id_here
GOOGLE_CLIENT_SECRET=your_google_client_secret_here
SESSION_SECRET=your_random_session_secret_here
FRONTEND_URL=http://localhost:3000

Important: Generate a strong random string for SESSION_SECRET. You can use:

node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

3. API Endpoints

Initiate Google Login

GET /api/auth/google

Redirects user to Google's OAuth consent screen.

Google Callback (handled automatically)

GET /api/auth/google/callback

Google redirects here after authentication.

Success Redirect

After successful authentication, user is redirected to:

{FRONTEND_URL}/auth/success?user={userData}

Failure Redirect

On authentication failure, user is redirected to:

{FRONTEND_URL}/login?error=google_auth_failed

4. Frontend Integration

Add Google Login Button

const handleGoogleLogin = () => {
  // Redirect to backend Google auth endpoint
  window.location.href = 'http://localhost:5000/api/auth/google';
};

// In your JSX
<button onClick={handleGoogleLogin}>
  Sign in with Google
</button>

Handle Success Callback

Create a route to handle the success redirect (e.g., /auth/success):

import { useEffect } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';

function AuthSuccess() {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();

  useEffect(() => {
    const userParam = searchParams.get('user');
    if (userParam) {
      try {
        const userData = JSON.parse(decodeURIComponent(userParam));
        // Store user data in your state management (Redux, Context, etc.)
        localStorage.setItem('user', JSON.stringify(userData));
        // Redirect to home/dashboard
        navigate('/');
      } catch (error) {
        console.error('Error parsing user data:', error);
        navigate('/login');
      }
    }
  }, [searchParams, navigate]);

  return <div>Authenticating...</div>;
}

5. User Model Updates

The User model now supports:

  • googleId: Google user ID
  • email: User's email (from Google)
  • authProvider: "local" or "google"
  • password: Optional (not required for Google users)
  • gender: Optional (not required for Google users)

6. Testing

  1. Start your backend server:

    npm run server
  2. Navigate to:

    http://localhost:5000/api/auth/google
    
  3. You should be redirected to Google's login page

  4. After successful login, you'll be redirected to your frontend with user data

7. Production Deployment

When deploying to production:

  1. Update Google OAuth credentials:

    • Add production callback URL in Google Console
    • Update FRONTEND_URL in production .env
  2. Ensure NODE_ENV=production for secure cookies

  3. Use HTTPS for both frontend and backend

8. Security Notes

  • ✅ Never commit .env file to version control
  • ✅ Use strong random strings for SESSION_SECRET
  • ✅ Enable HTTPS in production
  • ✅ Keep Google Client Secret secure
  • ✅ Regularly rotate secrets
  • ✅ Add rate limiting to auth endpoints (recommended)

9. Troubleshooting

Issue: "Redirect URI mismatch"

  • Ensure the callback URL in Google Console exactly matches your backend route

Issue: "Session not persisting"

  • Check CORS configuration includes credentials: true
  • Ensure frontend sends requests with credentials: 'include'

Issue: "User not authenticated"

  • Verify SESSION_SECRET is set in .env
  • Check that session middleware is initialized before passport

📝 Example Flow

  1. User clicks "Sign in with Google" on frontend
  2. Frontend redirects to http://localhost:5000/api/auth/google
  3. Backend redirects to Google's OAuth consent screen
  4. User authorizes the app
  5. Google redirects back to http://localhost:5000/api/auth/google/callback
  6. Backend creates/finds user, generates JWT token
  7. Backend redirects to frontend with user data
  8. Frontend stores user data and JWT cookie
  9. User is logged in! 🎉

🔗 Useful Links