normogen/backend/AUTH-MIDDLEWARE-FIX.md

2.3 KiB

🔴 Critical Issue Found: Auth Middleware Blocking All Requests

Problem

ALL API endpoints (including public ones) are returning 401 Unauthorized.

Root Cause

In main.rs, the auth middleware was applied to ALL routes using:

let app = Router::new()
    .route("/health", get(handlers::health_check))  // Public!
    .route("/api/auth/login", post(handlers::login))  // Public!
    .route("/api/users/me", get(handlers::get_profile))  // Protected
    .route_layer(axum_middleware::from_fn_with_state(
        app_state.clone(),
        crate::middleware::auth::jwt_auth_middleware  // ← Applied to ALL routes!
    ))
    .with_state(app_state);

The route_layer applies the middleware to all routes in the router, including public ones like /health and /api/auth/login.

Solution Applied

Split routes into public and protected routers:

// Public routes (no auth required)
let public_routes = Router::new()
    .route("/health", get(handlers::health_check))
    .route("/ready", get(handlers::ready_check))
    .route("/api/auth/register", post(handlers::register))
    .route("/api/auth/login", post(handlers::login))
    .route("/api/auth/refresh", post(handlers::refresh_token))
    .route("/api/auth/logout", post(handlers::logout))
    .layer(/* logging and CORS */);

// Protected routes (auth required)
let protected_routes = Router::new()
    .route("/api/users/me", get(handlers::get_profile))
    .route_layer(jwt_auth_middleware)  // ← Only applied to protected routes!

// Merge them together
let app = public_routes.merge(protected_routes).with_state(app_state);

Test Results Before Fix

$ curl http://10.0.10.30:6800/health
HTTP Status: 401  ← Should be 200!

$ curl -X POST http://10.0.10.30:6800/api/auth/register
HTTP Status: 401  ← Public endpoint blocked!

Expected Results After Fix

$ curl http://10.0.10.30:6800/health
HTTP Status: 200  ← OK!

$ curl -X POST http://10.0.10.30:6800/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "test@example.com", "password": "SecurePassword123!"}'
HTTP Status: 200  ← OK! Returns JWT tokens

$ curl http://10.0.10.30:6800/api/users/me
HTTP Status: 401  ← Correct! Needs auth token

Next Steps

  1. Pull the updated code
  2. Restart the container: docker compose restart backend
  3. Test the API: ./test-api-remote.sh