Broken user authentication

Protect accounts through password verification, login-attempt limits, and session management.

Description

Guessable passwords, unrestricted login attempts, missing multifactor authentication, and poorly managed sessions can expose a user’s account.

Potential impact

Someone who takes over an account may access sensitive information available to that user. A compromised administrator account may also allow changes to system settings or data.

Remediation

  • Require sufficient password length and block common or breached passwords. Character-composition rules alone cannot establish strength. Enable multifactor authentication (MFA).
  • Track attempts separately by account and client address in a shared store. Apply a delay or temporary lockout when a limit is reached.
  • Use established authentication and session libraries for Django, Flask, or FastAPI. Configure session expiration and prevent pre-login session IDs from being reused as authenticated sessions.

Examples

These are authentication excerpts. Models, shared stores, routing, and dependencies require separate configuration. Apply CSRF protection to browser cookie authentication and use HTTPS. Generate session and token-signing secrets with sufficient randomness and inject them externally.

Django

Before

python
# Before
from django.contrib.auth import authenticate

def login_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)
    if user is not None:
        # Login succeeded
        ...
    else:
        # Login failed
        ...

After

python
# After
import hashlib
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.core.cache import cache
from django.http import HttpResponse
from django.views.decorators.http import require_POST

MAX_USER_ATTEMPTS = 5
MAX_IP_ATTEMPTS = 20
ATTEMPT_WINDOW = 5 * 60

def login_attempt_keys(request, username):
    remote_addr = request.META.get('REMOTE_ADDR', 'unknown')
    user_key = hashlib.sha256(username.casefold().encode()).hexdigest()
    ip_key = hashlib.sha256(remote_addr.encode()).hexdigest()
    return [f'login:user:{user_key}', f'login:ip:{ip_key}']

def increment_login_attempt(key):
    cache.add(key, 0, timeout=ATTEMPT_WINDOW)
    try:
        return cache.incr(key)
    except ValueError:
        cache.set(key, 1, timeout=ATTEMPT_WINDOW)
        return 1

def consume_login_attempt(user_key, ip_key):
    # Check the IP limit first to bound the creation of cache keys for arbitrary usernames.
    if increment_login_attempt(ip_key) > MAX_IP_ATTEMPTS:
        return False
    return increment_login_attempt(user_key) <= MAX_USER_ATTEMPTS

@require_POST
def login_view(request):
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    user_attempt_key, ip_attempt_key = login_attempt_keys(request, username)
    if not consume_login_attempt(user_attempt_key, ip_attempt_key):
        return HttpResponse("Too many login attempts", status=429)

    user = authenticate(request, username=username, password=password)
    if user is None:
        return HttpResponse("Invalid credentials", status=401)

    # Reset only the successful account’s counter. Keep the IP counter until it expires
    # so signing in to another account cannot clear that limit.
    cache.delete(user_attempt_key)
    login(request, user)
    return HttpResponse("Logged in")

@login_required
def sensitive_view(request):
    # Handle sensitive data here.
    return HttpResponse("Sensitive data")

Explanation:

  • Before: The handler checks the password. Check whether another layer limits attempts and creates the login session.
  • After: A shared Django cache with atomic increments limits accounts and IP addresses separately. A successful login clears only the account counter, leaving the IP limit in place until expiry. login() creates the session and login_required protects sensitive views. Behind a reverse proxy, configure REMOTE_ADDR to contain a trusted client address.

Flask

Before

python
# Before
from flask import Flask, request
from werkzeug.security import check_password_hash

app = Flask(__name__)

@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    password = request.form['password']
    user = User.query.filter_by(username=username).first()
    if user and check_password_hash(user.password, password):
        # Login succeeded
        ...
    else:
        # Login failed
        ...

After

python
# After
import hashlib
import os
from flask import Flask, request, redirect, url_for
from werkzeug.security import check_password_hash, generate_password_hash
from flask_login import LoginManager, login_user, login_required
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address

app = Flask(__name__)
flask_secret = os.environ['FLASK_SECRET_KEY']
if len(flask_secret) < 32:
    raise RuntimeError('FLASK_SECRET_KEY must contain at least 32 characters')
app.config.update(
    SECRET_KEY=flask_secret,
    SESSION_COOKIE_HTTPONLY=True,
    SESSION_COOKIE_SECURE=True,
    SESSION_COOKIE_SAMESITE='Lax',
)
login_manager = LoginManager()
login_manager.init_app(app)
dummy_password_hash = generate_password_hash(os.urandom(32).hex())
limiter = Limiter(
    key_func=get_remote_address,
    app=app,
    storage_uri=os.environ['RATELIMIT_STORAGE_URI'],
)

@login_manager.user_loader
def load_user(user_id):
    # The User model implements UserMixin and returns a stable primary key from get_id().
    return User.query.filter_by(id=user_id).first()

def username_rate_key():
    username = request.form.get('username', '').casefold()[:128]
    return hashlib.sha256(username.encode()).hexdigest()

@app.route('/login', methods=['POST'])
@limiter.limit('20 per 5 minutes', key_func=get_remote_address)
@limiter.limit('5 per 5 minutes', key_func=username_rate_key)
def login():
    username = request.form.get('username', '')
    password = request.form.get('password', '')
    if not username or len(username) > 128 or not password or len(password) > 1024:
        return "Invalid credentials", 400

    user = User.query.filter_by(username=username).first()
    stored_hash = user.password if user is not None else dummy_password_hash
    password_is_valid = check_password_hash(stored_hash, password)
    if user is not None and password_is_valid:
        login_user(user)
        return redirect(url_for('dashboard'))
    return "Invalid credentials", 401

@app.route('/dashboard')
@login_required
def dashboard():
    # Handle sensitive data here.
    return "Sensitive data"

Explanation:

  • Before: The handler checks the password. Check whether another layer limits attempts and creates the login session.
  • After: Flask-Limiter uses a shared external store for separate account and IP limits. A dummy hash is checked for unknown accounts. The session uses a secret from the environment and protected cookies, and user_loader restores the user on later requests. Place @login_required directly below @app.route so Flask registers the protected handler.

FastAPI

Before

python
# Before
from fastapi import FastAPI, Request

app = FastAPI()

@app.post("/login")
async def login(request: Request):
    form_data = await request.form()
    username = form_data['username']
    password = form_data['password']
    user = get_user_by_username(username)
    if user and user.password == password:
        # Login succeeded
        ...
    else:
        # Login failed
        ...

After

python
# After
import hashlib
import os
from fastapi import FastAPI, Depends, HTTPException, Request
from fastapi.security import OAuth2PasswordRequestForm
from fastapi_login import LoginManager
from pwdlib import PasswordHash
from redis.asyncio import Redis

app = FastAPI()
jwt_secret = os.environ['JWT_SECRET']
if len(jwt_secret) < 32:
    raise RuntimeError('JWT_SECRET must contain at least 32 characters')
manager = LoginManager(jwt_secret, token_url="/auth/token")
password_hash = PasswordHash.recommended()
# Use the same password-hash verification path for unknown accounts.
dummy_password_hash = password_hash.hash(os.urandom(32))
redis = Redis.from_url(os.environ['REDIS_URL'], decode_responses=True)

ATTEMPT_WINDOW = 5 * 60
MAX_USER_ATTEMPTS = 5
MAX_IP_ATTEMPTS = 20

CONSUME_ATTEMPT = """
local ip_attempts = redis.call('INCR', KEYS[1])
if ip_attempts == 1 then
  redis.call('EXPIRE', KEYS[1], ARGV[1])
end
if ip_attempts > tonumber(ARGV[2]) then
  return 0
end

local user_attempts = redis.call('INCR', KEYS[2])
if user_attempts == 1 then
  redis.call('EXPIRE', KEYS[2], ARGV[1])
end
if user_attempts > tonumber(ARGV[3]) then
  return 0
end
return 1
"""

async def consume_login_attempt(username, client_address):
    user_digest = hashlib.sha256(username.casefold().encode()).hexdigest()
    ip_digest = hashlib.sha256(client_address.encode()).hexdigest()
    user_key = f'login:user:{user_digest}'
    ip_key = f'login:ip:{ip_digest}'
    allowed = await redis.eval(
        CONSUME_ATTEMPT,
        2,
        ip_key,
        user_key,
        ATTEMPT_WINDOW,
        MAX_IP_ATTEMPTS,
        MAX_USER_ATTEMPTS,
    )
    return allowed == 1, user_key

@manager.user_loader()
def load_user(username: str):
    return get_user_by_username(username)

@app.post("/auth/token")
async def login(request: Request, form_data: OAuth2PasswordRequestForm = Depends()):
    username = form_data.username
    password = form_data.password
    if not username or len(username) > 128 or not password or len(password) > 1024:
        raise HTTPException(status_code=400, detail="Invalid credentials")

    # Use the client address verified by the ASGI server instead of trusting forwarded headers directly.
    client_address = request.client.host if request.client else 'unknown'
    allowed, user_attempt_key = await consume_login_attempt(username, client_address)
    if not allowed:
        raise HTTPException(status_code=429, detail="Too many login attempts")

    user = load_user(username)
    stored_hash = user.password_hash if user is not None else dummy_password_hash
    password_is_valid = password_hash.verify(password, stored_hash)
    if user is None or not password_is_valid:
        raise HTTPException(status_code=401, detail="Invalid credentials")

    # Keep the IP counter so signing in to one account cannot clear its limit.
    await redis.delete(user_attempt_key)
    access_token = manager.create_access_token(data={"sub": username})
    return {"access_token": access_token, "token_type": "bearer"}

@app.get("/dashboard")
async def dashboard(current_user = Depends(manager)):
    # Handle sensitive data here.
    return {"detail": "Sensitive data"}

Explanation:

  • Before: The handler compares plaintext passwords and does not limit attempts.

  • After: An atomic Redis Lua script checks the IP limit first. If the IP limit is exceeded, it creates no new account keys, restricting attempts across accounts and cache growth. A successful login clears only the account counter.

    The password check uses the recommended hash and a dummy hash for unknown accounts to make account enumeration harder. The token-signing secret comes from the environment and must be sufficiently strong. Protect endpoints with an authentication dependency, and configure the ASGI server to accept forwarded headers only from trusted proxies.

References