Security-Focused Session Middleware

SESSION HARDENING.

/// DJANGO_SESSION_INTEGRITY_CONTROLS Session continuity signals, privacy-aware audit logging, and revocable gates. Three hookable middleware classes for Django.

REFERENCE CONTROLS

NIST AC-12 NIST SC-23 NIST AU-3 OWASP DJANGO 4.2+ PYTHON 3.10+

Three Drop-In Middleware

Each class solves a distinct security problem. Use one, two, or all three — they compose cleanly.

SessionSecurity

Applies configurable request-context continuity signals, absolute and idle timeouts, and selected claim-drift checks.

  • IP + User-Agent fingerprint binding
  • 8h absolute / 30min idle timeouts
  • JWT claim drift detection
  • Customizable exempt paths

AuditMiddleware

Privacy-aware authenticated-request events with keyed IP pseudonyms, safe field handling, and customizable identity hooks.

  • Per-request audit events
  • Customizable identity extraction
  • AU-3 / AU-12 reference structure
  • Hookable via method overrides

GateMiddleware

Base class for building cacheable conditional gates — compliance checks, onboarding flows, feature flags.

  • Cacheable gate results
  • Configurable fail-open / fail-closed
  • Custom check + on_reject hooks
  • Composable with other middleware

SECURITY CAPABILITIES.

Defence-in-depth controls for an existing, correctly configured Django authentication and session stack.

Fingerprint Binding

Configurable IP and User-Agent continuity signals can invalidate a session when its request context changes.

  • IP address binding (configurable)
  • User-Agent binding (configurable)
  • Trusted proxy depth support

Timeout Enforcement

Dual timeout strategy — absolute limit prevents stale sessions, idle limit catches abandoned ones.

  • 8-hour absolute timeout (default)
  • 30-minute idle timeout (default)
  • Supports AC-12-oriented timeout policy

Claim Drift Detection

Detects when selected authenticated claims change mid-session and applies the configured rejection response.

  • Monitors critical claims per request
  • Customizable claim selection
  • SC-23-oriented continuity control

Audit Trail

Structured authenticated-request events with keyed IP pseudonyms, field sanitization, and customizable identity hooks.

  • Structured JSON audit events
  • Exempt path filtering
  • AU-3/AU-12-oriented event structure

Gate lifecycle

Revocable cached decisions

Use TTL rechecks, explicit invalidation, shared state versions, or sticky_pass_max_age so long-lived sessions do not retain stale gate decisions.

Authorization still belongs in the application's authorization layer.

Audit privacy

Keyed pseudonyms and safe fields

Client IPs use keyed HMAC-SHA256 pseudonyms, attacker-influenced strings are sanitized, and exempt paths respect segment boundaries.

Custom fields and deterministic tokens can still be personal data and require retention/access controls.

Agent interface

Review-first MCP guidance

The packaged sessionarmor-mcp command helps agents reason about middleware ordering, settings, audit hooks, gate design, and rollout plans.

The public contract assumes no source, secret, or production-session access.

Designed for Hookability

Every middleware class is designed to be subclassed. Override the methods you need, keep the defaults for everything else.

Custom Claim Selection

Override `get_critical_claims()` to define which Auth0/OIDC claims trigger drift detection.

Custom Login URLs

Override `get_login_url()` for platform-specific login flows — multi-tenant ready out of the box.

Gate Pattern

Build compliance gates, onboarding flows, or feature flags by subclassing `GateMiddleware` with a single `check()` method.

middleware/compliance.py
from session_armor import GateMiddleware
from django.shortcuts import redirect

class ComplianceGate(GateMiddleware):
    gate_id = 'compliance'
    cache_ttl_setting = 'COMPLIANCE_CACHE_TTL'
    default_cache_ttl = 3600
    fail_open = False

    def check(self, request) -> bool:
        return user_accepted_terms(request)

    def on_reject(self, request):
        return redirect('/accept-terms/')

INTEGRATION

1 Install the package

$ pip install SessionArmor

2 Add middleware to settings.py

# settings.py

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    # ... your auth middleware ...
    'session_armor.session.SessionSecurityMiddleware',
    'session_armor.audit.AuditMiddleware',
    # ... rest of your middleware ...
]

# Optional settings (shown with defaults)
SESSION_ABSOLUTE_TIMEOUT = 28800      # 8 hours
SESSION_IDLE_TIMEOUT = 1800           # 30 minutes
SESSION_BIND_IP = True
SESSION_BIND_USER_AGENT = True
SESSION_DETECT_CLAIM_DRIFT = True
SESSION_ARMOR_TRUSTED_PROXY_DEPTH = 1  # Match the real proxy chain
SESSION_ARMOR_AUDIT_PEPPER = SECRET_KEY  # Prefer a dedicated secret

Security blueprint

How teams harden Django sessions in production

SessionArmor is designed for staged adoption. Start with session security, add audit logging, then build custom gates — each middleware works independently.

Phase 1 — Harden

Add SessionSecurityMiddleware. Bind sessions to fingerprints, enforce timeouts, and enable claim drift detection.

Phase 2 — Observe

Add AuditMiddleware. Capture structured audit events for every authenticated request. Feed into your SIEM.

Phase 3 — Gate

Build custom GateMiddleware subclasses for compliance checks, onboarding flows, and feature flags.

Security controls teams verify before shipping

  • • Fingerprints are continuity signals, not proof of device identity.
  • • Absolute and idle timeout behavior is tested against the application policy.
  • • Proxy depth matches the real ingress path so client-supplied forwarding data is not trusted accidentally.
  • • Audit fields, retention, access controls, and gate revocation behavior are reviewed before rollout.