Back to Hub

Building AuthSecurity: Django, Sessions, and TOTP 2FA

AuthSecurity login interface AuthSecurity two-factor authentication screen

The problem

Authentication looked simple in lecture slides until I tried to implement it end to end. I wanted a project that forced me to think about sessions, password handling, CSRF, and second factors - not just a login form that worked on my machine.

AuthSecurity pairs a Django REST Framework backend with a vanilla JavaScript frontend. No React layer in the middle: I wanted to stay close to the HTTP mechanics.

Research & Concepts

Session-based login means the server creates a session after a successful password check and sends back a session cookie. Later requests include that cookie so the server knows who I am without re-entering a password. The tradeoff is server-side state and careful cookie settings - but for a learning app it made the flow easy to follow.

CSRF matters because browsers attach cookies automatically. Without a CSRF token on mutating requests, another site could trick my browser into calling logout or account-changing endpoints while I am logged in. Django ships CSRF middleware; I still had to wire the token through the vanilla JS fetch calls.

TOTP (time-based one-time passwords) adds a second step after the password: an authenticator app generates a six-digit code from a shared secret that rotates every thirty seconds (RFC 6238). I used pyotp and QR setup so Google Authenticator or Authy could enroll the device. Password-only auth proves something I know; TOTP adds something I have.

Architecture

The backend owns user models, serializers, and API views under /api/auth/. The static frontend pages (register, login, dashboard) call those endpoints and redirect based on auth state.

  • Registration. Email format validation and password rules before a user row is created.
  • Session login and logout. Cookie-backed sessions via Django REST Framework.
  • TOTP 2FA. Setup and verify endpoints after primary password auth.
  • CSRF on mutating requests. Token read from cookies and sent on POST from the frontend.

What I learned

Security features are mostly edge cases: expired sessions, replayed tokens, a lost phone with no backup codes, and error messages that accidentally reveal whether an email exists. Building 2FA end to end made the threat model tangible instead of theoretical.

This runs locally as a learning stack - not something I would deploy as-is without hardening rate limits, recovery flows, and CSP headers on the static frontend.

What I'd improve next

Recovery codes for 2FA, rate limiting on login attempts, and automated tests around the auth flow. I would also tighten Content Security Policy headers on the static frontend.

Source code