Introduction

Welcome to the lesson on OAuth error handling! Building on our previous lesson about state parameter validation, we'll now explore how to handle the most common errors that occur during OAuth flows. You'll learn how to implement simple but effective error handling that keeps your application secure and users informed. Let's get started! 🛡️

Common OAuth Errors

When implementing OAuth, you'll encounter three main types of errors:

  • Setup errors: When your OAuth configuration is incomplete or misconfigured.
  • User denials: When users click "Cancel" on the consent screen.
  • Server errors: When something goes wrong with the OAuth provider or your server.

These cover 90% of OAuth error scenarios you'll encounter in real applications.

How Poor Error Handling Creates Vulnerabilities

Without proper error handling, attackers can:

  1. Learn about your OAuth configuration through detailed error messages.
  2. Bypass security checks if errors aren't handled consistently.
  3. Cause your application to crash or behave unexpectedly.

For example, if your app crashes when it receives an invalid OAuth response, an attacker knows they've found a potential weakness to exploit.

Simple Error Handling Implementation

Let's build a robust error handling system for our OAuth implementation.

Define Error Types

First, we'll create an enum to categorize the different types of OAuth errors we might encounter. This makes our error handling more organized and easier to maintain.

from enum import Enum

# Define the main OAuth error types we need to handle
class OAuthErrorType(Enum):
    USER_DENIED = 'user_denied'     # User clicked "Cancel" 
    SERVER_ERROR = 'server_error'   # OAuth provider had issues
    SETUP_ERROR = 'setup_error'     # OAuth configuration issues
Create User-Friendly Messages

Next, we'll map each error type to a clear, helpful message that users can understand. These messages should guide users on what to do next without revealing sensitive technical details.

# Map error types to user-friendly messages
# Keep messages simple and actionable
error_messages = {
    OAuthErrorType.USER_DENIED: 'Authentication was cancelled. You can try again or use password login.',
    OAuthErrorType.SERVER_ERROR: 'A server error occurred. Please try again or contact support.',
    OAuthErrorType.SETUP_ERROR: 'OAuth setup incomplete. Please check your User model configuration.'
}
Simple Error Handler

Now we'll create a centralized error handler that logs the error for debugging and redirects users to a helpful error page.

from datetime import datetime
from urllib.parse import quote
from fastapi.responses import RedirectResponse

# Centralized error handler for OAuth errors
# Logs for debugging but shows user-friendly messages
def handle_oauth_error(error_type: OAuthErrorType):
    # Log the error for debugging - helps with troubleshooting
    print('OAuth Error:', {
        'type': error_type.value,
        'timestamp': datetime.now().isoformat()
    })
    
    # Get the user-friendly message for this error type
    message = error_messages.get(
        error_type, 
        'An authentication error occurred. Please try again.'
    )
    
    # Redirect to login page with error information
    # Users will see a helpful message and can try again
    return RedirectResponse(
        url=f'/login?error={error_type.value}&message={quote(message)}'
    )
Update Your OAuth Callback Handler

Now we'll modify our OAuth callback handlers to include proper error checking using try-except blocks. This handles both OAuth provider errors and our own setup validations.

from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
import logging

@router.get('/oauth/google/callback')
async def google_oauth_callback(db: AsyncSession = Depends(get_db)):
    """Handles the successful mock Google login with error handling."""
    try:
        # Get or create the OAuth user and generate token
        token = await _get_or_create_oauth_user_and_token(
            db,
            'John Doe (Google)',
            'john.google@example.com',
            'google'
        )
        
        # Check if token generation was successful
        # This catches configuration issues
        if not token:
            return handle_oauth_error(OAuthErrorType.SETUP_ERROR)
        
        # If we get here, the OAuth flow was successful
        # Redirect with token and success message
        from urllib.parse import quote
        return RedirectResponse(
            url=f'/?token={token}&provider=google&message={quote("Successfully logged in with google OAuth!")}'
        )
        
    except Exception as error:
        # Log the actual error for debugging
        logging.error(f'Google OAuth error: {error}')
        # Return user-friendly error message
        return handle_oauth_error(OAuthErrorType.SERVER_ERROR)
Handle User Denials

When users click "Cancel" on the OAuth consent screen, handle it gracefully:

@router.get("/denied")
async def oauth_denied():
    """Handle user denial (when they click 'Cancel' on OAuth screen)"""
    return handle_oauth_error(OAuthErrorType.USER_DENIED)
Complete Error Handling Module

Here's the complete error handling utility module that you'll create:

# utils/oauth_errors.py
from enum import Enum
from fastapi.responses import RedirectResponse
from datetime import datetime
from urllib.parse import quote

class OAuthErrorType(Enum):
    USER_DENIED = 'user_denied'
    SERVER_ERROR = 'server_error'
    SETUP_ERROR = 'setup_error'

def handle_oauth_error(error_type: OAuthErrorType):
    error_messages = {
        OAuthErrorType.USER_DENIED: 'Authentication was cancelled. You can try again or use password login.',
        OAuthErrorType.SERVER_ERROR: 'A server error occurred. Please try again or contact support.',
        OAuthErrorType.SETUP_ERROR: 'OAuth setup incomplete. Please check your User model configuration.'
    }
    
    # Log for debugging (production would use proper logging)
    print('OAuth Error:', {
        'type': error_type.value,
        'timestamp': datetime.now().isoformat()
    })
    
    message = error_messages.get(
        error_type, 
        'An authentication error occurred. Please try again.'
    )
    return RedirectResponse(
        url=f'/login?error={error_type.value}&message={quote(message)}'
    )
Conclusion and Next Steps

In this lesson, we've added simple but effective error handling to our OAuth implementation. We now properly handle setup errors, user denials, and server errors with clear, user-friendly messages.

Key points:

  • Handle the three most common OAuth error types.
  • Log errors for debugging but don't expose sensitive details to users.
  • Always wrap OAuth callbacks in try-except blocks for robust error handling.
  • Provide clear, actionable error messages to users.

In the next practice, you'll implement this error handling in your OAuth system to make it both secure and user-friendly! 🚀

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal