GeoIP in Django and FastAPI: trusted IP extraction, antifraud hooks, and audit logging
GeoIP in Django and FastAPI: trusted IP and antifraud hooks
Python backends often fail fraud checks because IP extraction is weak or audit trails are incomplete. This guide focuses on strict trust boundaries, reusable hooks, and event logging that supports compliance and post incident analysis.
Trusted client IP order
- If source is not trusted proxy, use remote address directly.
- If trusted proxy, evaluate
CF-Connecting-IP, thenX-Real-IP, then firstX-Forwarded-For. - Validate format and reject private ranges where policy requires public IP.
FastAPI dependency example
def geo_context(request: Request):
ip = resolve_client_ip(request)
user_id = getattr(request.state, "user_id", "anon")
ctx = geo_client.lookup(ip=ip, user_id=user_id)
request.state.geo_ctx = ctx
return ctx
Django middleware example
class GeoRiskMiddleware:
def __call__(self, request):
ip = resolve_client_ip(request)
request.geo_ctx = geo_client.lookup(ip=ip, user_id=get_user_key(request))
return self.get_response(request)
Case study: payout fraud control
A fintech API used GeoIP hooks on payout initiation. High risk + new country + failed login burst triggered step up. Analysts received structured event logs with rule IDs and confidence fields, reducing investigation time.
Audit fields to store
- request_id, user_id, session_id, ip, country, city, ASN.
- risk score, confidence, proxy flags, impossible travel signal.
- decision action, policy rule id, challenge result.
SEO intent coverage
This content targets queries like GeoIP Django middleware, FastAPI fraud detection, and trusted IP extraction Python, attracting teams with real implementation intent.
Use GeoIP.space in Python stack
GeoIP.space returns consistent fields for Python antifraud workflows, from auth to payouts. Start now and validate on staging traffic.