Authentication: Securing Your Application
DraftURL: https://ruvebal.github.io/web-atelier-udit/lessons/en/react/react-authentication/
π Table of Contents
- π― Sprint Goal
- π Position in Journey
- π§ Learning Objectives
- ποΈ What Weβll Build This Sprint
- π§ Integration Options
- β οΈ Security Critical Points
- π Methodology: Atelier Practice
- π Sprint Deliverables
- π Lesson Navigation
- π Key Concepts Preview
β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
Option A: Laravel Sanctum (Recommended for Full-Stack)
// 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
localStoragefor 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.β