WEB ATELIER (UDIT) Β· Learning by doing, with theory, practice and shared reflection

Authentication: Securing Your Application

Draft

URL: https://ruvebal.github.io/web-atelier-udit/lessons/en/react/react-authentication/

πŸ“‹ Table of Contents

β€œAuth is where security, UX, and architecture collide. Handle with care.”


🎯 Sprint Goal

By the end of this sprint: Implement complete authenticationβ€”login, logout, registration, protected routes, and persistent sessionsβ€”with security best practices.


πŸ“ Position in Journey

Sprint Focus Your App Grows
8. Routing Navigation Multi-page structure
9. Backend Data fetching Real data, real app
β†’ 10. Auth Security User sessions
11. Testing Quality Reliable codebase

🧭 Learning Objectives

By the end of this lesson, you will:

  • Understand JWT vs session-based authentication
  • Build login, logout, and registration flows
  • Store tokens securely (and know what’s NOT secure)
  • Implement AuthContext with user state
  • Protect routes based on auth status
  • Handle token refresh and expiration

πŸ—οΈ What We’ll Build This Sprint

Auth Architecture

src/
β”œβ”€β”€ auth/
β”‚   β”œβ”€β”€ AuthContext.jsx      // User state + login/logout
β”‚   β”œβ”€β”€ AuthProvider.jsx     // Wraps app, checks token
β”‚   β”œβ”€β”€ useAuth.js           // Consumer hook
β”‚   └── ProtectedRoute.jsx   // Route guard
β”œβ”€β”€ pages/
β”‚   β”œβ”€β”€ Login.jsx            // Login form
β”‚   β”œβ”€β”€ Register.jsx         // Registration form
β”‚   └── Profile.jsx          // Protected page
└── api/
    └── auth.js              // Login/logout API calls

πŸ”§ Integration Options

// Laravel Sanctum with cookies (CSRF protected)
await fetch('/sanctum/csrf-cookie', { credentials: 'include' });
const response = await fetch('/api/login', {
  method: 'POST',
  credentials: 'include',
  body: JSON.stringify({ email, password })
});

Option B: JWT with Laravel API

// JWT token flow
const { token } = await login(email, password);
localStorage.setItem('token', token); // ⚠️ Not ideal for production

// Attach to requests
headers: { 'Authorization': `Bearer ${token}` }

Option C: Firebase Auth (Quick Setup)

import { signInWithPopup, GoogleAuthProvider } from 'firebase/auth';
const provider = new GoogleAuthProvider();
const result = await signInWithPopup(auth, provider);
const user = result.user;

Option D: OAuth Providers (GitHub, Google)

// Redirect flow
window.location.href = '/api/auth/github/redirect';
// Callback handles token exchange

⚠️ Security Critical Points

❌ Don’t βœ… Do
Store JWT in localStorage Use httpOnly cookies
Trust client-side auth alone Validate on server every request
Log sensitive data Redact tokens in logs
Hardcode secrets Use environment variables
Skip HTTPS Always HTTPS in production

πŸŽ“ Methodology: Atelier Practice

The Sprint Rhythm

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ DAY 1: Auth Fundamentals                                β”‚
β”‚   β€’ Build AuthProvider and useAuth hook                 β”‚
β”‚   β€’ Create Login form with validation                   β”‚
β”‚   β€’ Test login flow with Laravel or Firebase            β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ DAY 2: Complete Auth Flow                               β”‚
β”‚   β€’ Registration with validation                        β”‚
β”‚   β€’ Wire ProtectedRoute to AuthContext                  β”‚
β”‚   β€’ Implement logout and session persistence            β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ DAY 3: Security Review                                  β”‚
β”‚   β€’ Peer security audit: find vulnerabilities           β”‚
β”‚   β€’ Handle edge cases: expired token, network error     β”‚
β”‚   β€’ Discussion: What attacks are you protecting against?β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

AI-Assisted Development Protocol

Task AI Role Your Role
Generate auth forms Scaffold with validation Add your UI components
Debug 401 errors Explain token lifecycle Fix refresh logic
Review security Suggest improvements Implement with understanding
Handle edge cases Propose error states Design for user trust

πŸ“ Sprint Deliverables

  • AuthContext with user state, login, logout, register
  • Login page with form validation and error handling
  • Register page with password confirmation
  • Protected routes redirecting unauthenticated users
  • Persistent session (user stays logged in on refresh)
  • Logout that clears all auth state
  • Security checklist reviewed with peer team
  • Reflection: What are the trade-offs of your auth approach?

πŸ”— Lesson Navigation

Previous Current Next
Backend Integration Authentication Testing

πŸ“š Key Concepts Preview

Non-negotiables (security + UX)

  • Never store access tokens in localStorage for serious apps (XSS risk). Prefer httpOnly cookies when possible.
  • Always implement loading + error states for auth actions (login/register/refresh).
  • Treat auth as state: anonymous | authenticating | authenticated | error.

Authentication vs Authorization

  • Authentication: who are you?
  • Authorization: what can you do?
  • In React: route guards are authorization; login is authentication.

Example: auth state as a discriminated union

// Auth state shape: status + optional user/error
// { status: 'anonymous' } | { status: 'authenticating' }
// | { status: 'authenticated'; user: { id, role? } }
// | { status: 'error'; message: string }

Practical checklist (student baseline)

  • CSRF/XSS awareness: sanitize/escape, never render untrusted HTML, protect cookies.
  • Session persistence: refresh on load, handle β€œexpired session” gracefully.
  • RBAC: at least 2 roles (e.g., user/admin) or 2 permission levels.

Reflection (Atelier)

πŸ’­ Which threat model did you assume? What is the most realistic attack on your project?

πŸ’­ Where did AI helpβ€”and where would following AI blindly create a security bug?

Koan

β€œIf convenience defeats security, you built a demoβ€”not a system.”


β€œTrust is earned in drops and lost in buckets. Auth code is no different.”