Chapter 7: Authentication & Identity Security
Securing a Flask application involves managing identity state across stateless HTTP requests. Flask provides a signed cookie-based session system, while extensions like Flask-Login and Flask-JWT-Extended provide the abstractions for user management and token-based authorization. For production systems, security is a mandate that requires cryptographically strong secrets, secure storage of credentials, and strict session lifecycle management.
I. Signed Cookie Sessions (ItsDangerous)
Flask sessions are client-side. Data is serialized, compressed, and cryptographically signed using the ItsDangerous library before being stored in a browser cookie.
- Tamper-Proof: Users cannot modify session data without the
SECRET_KEY. - Data Visibility: Since cookies are only encoded (not encrypted by default), users can read the session data. Never store PII (Personally Identifiable Information) or passwords in the Flask session.
II. Password Engineering: Argon2id
Storing plain-text or poorly hashed passwords (like MD5 or SHA1) is a critical security failure. Modern engineering standards require Argon2id, the winner of the Password Hashing Competition. It is resistant to GPU-based cracking, side-channel attacks, and provides tunable memory and time complexity to future-proof against hardware advances.
v=19$m=65536...
III. Production Anti-Patterns
- Hardcoded Secret Keys: Using
"dev-secret"in production. This allows attackers to forge administrative session cookies instantly. - JWT without Expiration: Issuing tokens with no
expclaim. These tokens are valid forever, making revocation impossible without a complex blacklist. - Session Fixation: Failing to call
session.clear()and generating a new session ID upon login, allowing an attacker to reuse a pre-auth cookie.
IV. Performance Bottlenecks
- Auth-DB Roundtrips: Querying the database to load the user object on every single request. Use a Cache-Aside pattern with Redis to store user metadata.
- Cookie Size Bloat: Storing large amounts of state in the session. Browsers limit cookies to 4KB; exceeding this can cause requests to be rejected by the reverse proxy.
- CPU Saturation during Login: Running Argon2 with excessively high parameters on a low-CPU web server, which can lead to Denial of Service during a login spike.