Problem
Implement a secure OAuth 2.0 Authorization Code flow to allow users to log in with their Google account. The flow should handle the complete lifecycle: initiating the login, handling the callback, exchanging the authorization code for tokens, fetching user profile information, and creating/linking the user account in your database.
Requirements
- Login Initiation: When a user clicks "Sign in with Google," redirect them to Google's authorization endpoint with the correct parameters.
- Callback Handling: After the user authorizes, Google redirects back to your
/api/auth/callback/google endpoint with an authorization code.
- Token Exchange: Exchange the authorization code for an access token and ID token.
- User Profile: Decode the ID token or call Google's userinfo endpoint to get the user's name, email, and profile picture.
- Account Linking: If a user with that email already exists, link the Google account. If not, create a new user account.
- Session Management: Create a session (JWT or server-side session) after successful authentication.
- Security: Prevent CSRF attacks using the
state parameter. Validate all tokens.
Constraints
- Use the Authorization Code flow (not Implicit flow).
- The
state parameter must be unpredictable and validated on callback.
- Access tokens should not be stored in localStorage (XSS risk).
- Handle edge cases: user denies permission, token exchange fails, email already registered with password.
- Support PKCE (Proof Key for Code Exchange) for additional security.
What to Design
- The complete OAuth flow with sequence diagram
- CSRF protection via the state parameter
- PKCE implementation
- Account creation vs. linking logic
- Session creation and token storage strategy