📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Cybersecurity and AI Security Authentication and Session Security

Authentication and Session Security

5 min read Quiz at the end
bcrypt for password hashing, TOTP for MFA, secure sessions with regeneration, and account lockout.

Authentication and Session Security

# Secure password storage
import bcrypt

# Hash (never store plain text)
hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt(rounds=12))

# Verify
bcrypt.checkpw(password.encode(), hashed)  # True/False

# Multi-Factor Authentication (MFA)
import pyotp
totp = pyotp.TOTP('user-secret-base32')
totp.now()           # '123456' - current OTP
totp.verify('123456') # True
# QR code setup: pyotp.totp.TOTP(secret).provisioning_uri(name='alice@example.com')

# Secure session management
from flask import session
import os
app.secret_key = os.urandom(32)  # random 256-bit key
session.permanent = True
app.permanent_session_lifetime = timedelta(hours=2)

# Session fixation prevention: regenerate after login
session.clear()
session['user_id'] = user.id

# Account lockout (prevent brute force)
MAX_ATTEMPTS = 5
LOCKOUT_DURATION = 900  # 15 minutes
if failed_attempts >= MAX_ATTEMPTS:
    lock_account(user_id, LOCKOUT_DURATION)
Topic Quiz · 1 questions

Test your understanding before moving on

1. Which password hashing algorithm is recommended for storing user passwords?
💡 bcrypt is slow by design (work factor), has a built-in salt, and is designed specifically for passwords.