Skip to content

Migrate authentication from localStorage to cookies for realistic CSRF demonstration #25

@kOaDT

Description

@kOaDT

Context

Currently, the CSRF vulnerability demonstration uses localStorage to store authentication tokens. While this works for educational purposes on the same domain, it doesn't accurately represent real-world CSRF attacks, which typically exploit cookie-based authentication.

Problem

The current implementation has limitations:

  • The attack only works when the malicious page is on the same domain (same-origin policy)
  • Real-world CSRF attacks exploit cookies that browsers automatically send cross-origin
  • The demonstration doesn't show the true cross-site nature of CSRF attacks
  • Students may not understand why CSRF is dangerous with cookie-based auth

Proposed Solution

Migrate the authentication system from localStorage to HTTP-only cookies with appropriate sameSite settings to demonstrate:

  1. True cross-site attacks: Malicious pages on external domains can trigger authenticated requests
  2. Cookie behavior: How browsers automatically include cookies in cross-origin requests
  3. SameSite protection: How sameSite: "strict" prevents CSRF attacks
  4. Real-world scenarios: More accurate representation of actual CSRF vulnerabilities

Implementation Plan

1. Backend Changes

Files to modify:

  • app/api/auth/login/route.ts - Set authentication cookie
  • app/api/auth/signup/route.ts - Set authentication cookie
  • app/api/auth/support-login/route.ts - Set authentication cookie
  • lib/server-auth.ts - Read from cookies instead of Authorization header

Changes needed:
// Set cookie on login
response.cookies.set("authToken", token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax", // Vulnerable to CSRF for demonstration
maxAge: 60 * 60 * 24 * 7,
path: "/",
});

// Read from cookie
export async function getAuthenticatedUser(request: NextRequest) {
const token = request.cookies.get("authToken")?.value;
if (!token) return null;
return decodeWeakJWT(token);
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    Status

    In progress

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions