Skip to content
iplogs.comSign up

Django: block VPN and proxy users with middleware

By Muntaha Shaheen · · updated · 7 min read

To block VPN and proxy users in Django, write a middleware whose process_view() runs only for named views such as login and signup. It works out the client IP from REMOTE_ADDR and reads X-Forwarded-For only when the request came from your own proxy, taking the rightmost address that is not one of yours. It sends that IP to POST https://iplogs.com/v1/check with a timeout, for example timeout=(2, 5). Cache full verdicts with Django's cache framework, using a backend shared between workers such as Redis. Return 403 when the verdict is vpn_detected, or when the address is flagged as a proxy and is not a privacy relay. Let the request through if the API fails, times out or returns 429, so an outage never blocks a signup. In Django REST Framework, use a permission class that raises PermissionDenied.

How the Django check runs

  1. The request reaches a named view

    process_view runs only for views such as login and signup.

  2. Work out the client IP

    REMOTE_ADDR, plus X-Forwarded-For only from your own proxy: the rightmost address that is not yours.

  3. Ask the API

    POST to /v1/check with a timeout, and cache full verdicts in a cache shared between workers.

  4. Decide

    403 for vpn_detected, or for a flagged proxy that is not a privacy relay. An error, a timeout or a 429 lets the request through.

The path of the Django middleware from view to verdict.

Django hands you request.META["REMOTE_ADDR"] and, on purpose, does nothing with X-Forwarded-For. The client-IP logic is yours to write, and it's where a VPN check goes wrong first: feed it the wrong address and it either judges your load balancer on every request or takes the client's word for who they are.

The code here uses a process_view middleware that matches URL names, plus a permission class for Django REST Framework, and it was run on Django 6.1 with DRF 3.18. If all you need is the API call from Python, the Python guide is shorter.

How do I block VPN users in Django?

Check the client IP in a middleware and return 403 when the API says vpn_detected, or flags the address as a proxy that isn't a privacy relay. The logic lives in one module, accounts/ipcheck.py: client_ip() works out the visitor's address, trusting X-Forwarded-For only from your proxies, and check() asks the API about it and caches the answer for 15 minutes. The middleware calls both for POSTs to the views you list in settings. Any failure along the way returns None, and None lets the request through.

How do I get the client IP in Django behind a proxy?

Read REMOTE_ADDR, and only look at X-Forwarded-For when REMOTE_ADDR is one of your own proxies. REMOTE_ADDR is the address of the socket peer, so a client can't change it with a header. Behind nginx, a load balancer or a CDN it holds the proxy's address instead of the visitor's.

Django doesn't parse X-Forwarded-For for you, and that was a decision. Django 1.0 shipped a SetRemoteAddrFromForwardedFor middleware; the 1.1 release notes removed it because the mechanism "cannot be made reliable enough for general-purpose use", and because having it in Django could lead developers to assume REMOTE_ADDR was safe. The working version needs one thing Django can't know: which addresses are yours.

# settings.py
# Addresses your own reverse proxies and load balancers connect from.
# 127.0.0.1 covers nginx or Caddy on the same host as Gunicorn/Uvicorn.
IPLOGS_TRUSTED_PROXIES = ["10.0.0.0/8", "127.0.0.1/32", "::1/128"]

# Views to check, by view_name (namespace:url_name).
IPLOGS_PROTECTED_VIEWS = {"accounts:signup", "login"}

Then walk the chain from the right. Each proxy appends the address it received the request from, so the rightmost address that isn't one of yours is the one your edge proxy saw. Everything to its left was supplied by the client and can be anything. Cloudflare follows the same convention: it appends the connecting address to any X-Forwarded-For the client sent, so its ranges belong in the list when it sits in front of you.

# accounts/ipcheck.py
import ipaddress
import logging

import requests
from django.conf import settings
from django.core.cache import cache

log = logging.getLogger(__name__)

API_URL = "https://iplogs.com/v1/check"
CACHE_SECONDS = 15 * 60
BACKOFF_KEY = "iplogs:backoff"


def _is_trusted(addr):
    return any(addr in ipaddress.ip_network(net) for net in settings.IPLOGS_TRUSTED_PROXIES)


def client_ip(request):
    """The visitor's IP, or "" if it can't be worked out safely."""
    try:
        remote = ipaddress.ip_address(request.META.get("REMOTE_ADDR", ""))
    except ValueError:
        return ""
    if not _is_trusted(remote):
        # Not one of our proxies, so X-Forwarded-For is whatever the client typed.
        return str(remote)
    hops = [h.strip() for h in request.META.get("HTTP_X_FORWARDED_FOR", "").split(",")]
    for hop in reversed([h for h in hops if h]):
        try:
            addr = ipaddress.ip_address(hop)
        except ValueError:
            return ""
        if not _is_trusted(addr):
            return str(addr)
    return ""

A malformed entry ends the walk with an empty string instead of skipping ahead to the next hop, and check() below treats an empty string as "don't know, allow".

If you use Django REST Framework throttling, check its NUM_PROXIES setting too. DRF's docs say that when X-Forwarded-For is present it is used to identify the client unless you configure NUM_PROXIES, so by default a client can pick its own throttle bucket.

How do I set a timeout on the API call with requests?

Pass timeout= to every requests call. Without it, in the library's own words, requests do not time out, so one hung connection ties up a worker for as long as it hangs. A (connect, read) tuple sets the two limits separately, and the read limit applies to each wait for bytes from the socket rather than to the whole response.

# accounts/ipcheck.py (continued)
def check(ip):
    """The iplogs verdict as a dict, or None when there is no answer (allow)."""
    if not ip or cache.get(BACKOFF_KEY):
        return None
    key = f"iplogs:{ip}"
    verdict = cache.get(key)
    if verdict is not None:
        return verdict

    try:
        resp = requests.post(API_URL, json={"ip": ip}, timeout=(2, 5))
    except requests.RequestException as exc:
        log.warning("iplogs check failed for %s: %s", ip, exc)
        return None

    if resp.status_code == 429:
        retry = resp.headers.get("Retry-After", "")
        cache.set(BACKOFF_KEY, True, int(retry) if retry.isdigit() else 60)
        return None
    if resp.status_code != 200:
        log.warning("iplogs returned %s for %s", resp.status_code, ip)
        return None
    try:
        verdict = resp.json()
    except ValueError:
        return None
    if not isinstance(verdict, dict):
        return None
    if verdict.get("mode") == "fast":
        return verdict  # in-memory answer once the daily quota is spent: don't keep it

    cache.set(key, verdict, CACHE_SECONDS)
    return verdict


def should_block(verdict):
    """A VPN or Tor exit, or an open or residential proxy. Privacy relays
    (iCloud Private Relay, Cloudflare WARP) report is_relay and pass, even
    though WARP alone scores vpn_detected."""
    if not verdict or verdict.get("is_relay"):
        return False
    return verdict.get("verdict") == "vpn_detected" or bool(verdict.get("is_proxy"))

The cache is read and written with plain get() and set(). cache.get_or_set() would be shorter, but it stores whatever the callable returns, a None from a failed call included, and that None would then stand in for a verdict for 15 minutes. Here only a successful full answer is written, so a timeout is retried on the next request. A first full check of an address the API hasn't seen takes about 3 seconds while it probes the address, and the API's own ceiling is 8, so the 5-second read limit cuts a few off; those fail open like any other error.

On a 429, which the API sends once you exceed 60 requests a minute, the Retry-After value becomes the lifetime of a backoff key, and no call goes out while that key exists. Every one of these paths returns None, and the middleware takes None as permission to continue, so an API outage never blocks a signup. The cache calls themselves aren't wrapped: if your Redis can go down, catch its errors too, or a cache outage turns into a 500.

Using httpx? The equivalent call is httpx.post(API_URL, json={"ip": ip}, timeout=httpx.Timeout(5.0, connect=2.0)), catching httpx.HTTPError. httpx already times out after 5 seconds by default; passing the timeout keeps the intent visible.

Pick the cache backend with care. The default LocMemCache is per-process, so four Gunicorn workers keep four separate caches and may each check the same IP. Django ships a Redis backend, django.core.cache.backends.redis.RedisCache, which shares one cache across workers and servers.

Sharing matters because the free limits apply to whoever makes the call, and that's your server: a ceiling of 60 requests a minute, plus 2,000 full checks per UTC day, no key or sign-up required. When the day's full checks run out, responses still arrive as HTTP 200, marked "mode": "fast" and built without live probes. You can ask for that mode on a hot path such as login by sending {"ip": ip, "mode": "fast"}. It is computed in microseconds (the network round trip still applies) without live probes, so it catches fewer unlisted VPNs, and check() above never caches it. Backfilling existing accounts is a job for POST /v1/bulk-check in a Celery task or a management command. It accepts up to 100 IPs per call, each one counting against the 2,000 daily full checks, and the pacing it allows is three calls in a burst, then one per 5 seconds.

How do I write Django middleware that blocks VPN IPs?

Do the work in process_view(), not __call__(). URL resolution has happened by then, so request.resolver_match tells you which view is about to run, and you can match on view names instead of string paths that drift as URLs change. Returning an HttpResponse from process_view() skips the view.

# accounts/middleware.py
from django.conf import settings
from django.http import HttpResponseForbidden

from . import ipcheck


class BlockAnonymousIPMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        return self.get_response(request)

    def process_view(self, request, view_func, view_args, view_kwargs):
        match = request.resolver_match
        if request.method != "POST" or match.view_name not in settings.IPLOGS_PROTECTED_VIEWS:
            return None

        verdict = ipcheck.check(ipcheck.client_ip(request))
        request.ip_verdict = verdict  # views can add friction for grey cases
        if ipcheck.should_block(verdict):
            return HttpResponseForbidden("Please turn off your VPN or proxy and try again.")
        return None
# settings.py
MIDDLEWARE = [
    # ... Django's defaults ...
    "accounts.middleware.BlockAnonymousIPMiddleware",
]

view_name includes the namespace (accounts:signup), while url_name doesn't. Checking only POSTs means the form itself still renders for everyone, and the decision happens when they submit it.

The middleware refuses vpn_detected, the band from 0.85 up (published VPN servers and Tor exits), and any address flagged is_proxy (open proxies and residential-proxy exits). A privacy relay (is_relay: iCloud Private Relay, Cloudflare WARP) always passes, which matters for WARP: its addresses score 0.85 on their own. Views can read request.ip_verdict for everything that got through. vpn_likely starts at 0.60, which is also where is_vpn turns true, and it's a reasonable point to create the account but require email verification, or to queue the order for review. suspicious (0.30 to 0.60) covers a lot of ordinary people, iCloud Private Relay users and staff on company VPNs among them, so log it rather than act on it. A clean result can still be a residential proxy, since the IP by itself gives almost nothing away about those exits.

How do I block VPN users in Django REST Framework?

Use a permission class, and raise PermissionDenied yourself rather than returning False. When a permission check returns False on a request that isn't authenticated, DRF answers with NotAuthenticated ("Authentication credentials were not provided.") instead of your message, and signup and login endpoints are where that happens.

# accounts/permissions.py
from rest_framework.exceptions import PermissionDenied
from rest_framework.permissions import BasePermission

from . import ipcheck


class NotFromAnonymousIP(BasePermission):
    def has_permission(self, request, view):
        verdict = ipcheck.check(ipcheck.client_ip(request))
        if ipcheck.should_block(verdict):
            # Raise instead of returning False: for a logged-out user DRF would
            # turn False into "Authentication credentials were not provided."
            raise PermissionDenied("Please turn off your VPN or proxy and try again.")
        return True

Add it with permission_classes = [NotFromAnonymousIP] on the signup view. DRF's Request keeps the standard HttpRequest attributes, request.META included, so client_ip() works unchanged.

How do I test the middleware?

Unit-test client_ip() with RequestFactory, and mock requests.post for the failure paths so the suite never needs the network:

# accounts/tests.py
from unittest import mock

import requests
from django.core.cache import cache
from django.test import RequestFactory, SimpleTestCase, override_settings

from accounts import ipcheck


@override_settings(IPLOGS_TRUSTED_PROXIES=["10.0.0.0/8"])
class ClientIPTests(SimpleTestCase):
    def ip(self, remote, forwarded=""):
        request = RequestFactory().get("/", REMOTE_ADDR=remote, HTTP_X_FORWARDED_FOR=forwarded)
        return ipcheck.client_ip(request)

    def test_header_from_a_direct_client_is_ignored(self):
        self.assertEqual(self.ip("203.0.113.7", "1.2.3.4"), "203.0.113.7")

    def test_rightmost_untrusted_hop_wins_behind_a_proxy(self):
        self.assertEqual(self.ip("10.0.0.5", "1.2.3.4, 198.51.100.9"), "198.51.100.9")

    def test_malformed_chain_gives_no_ip(self):
        self.assertEqual(self.ip("10.0.0.5", "not-an-ip"), "")


class CheckTests(SimpleTestCase):
    def setUp(self):
        cache.clear()

    @mock.patch("accounts.ipcheck.requests.post", side_effect=requests.Timeout)
    def test_fails_open_on_timeout(self, _post):
        self.assertIsNone(ipcheck.check("192.0.2.1"))

    @mock.patch("accounts.ipcheck.requests.post")
    def test_backs_off_after_429(self, post):
        post.return_value = mock.Mock(status_code=429, headers={"Retry-After": "30"})
        self.assertIsNone(ipcheck.check("192.0.2.2"))
        self.assertTrue(cache.get(ipcheck.BACKOFF_KEY))

    @mock.patch("accounts.ipcheck.requests.post")
    def test_fast_answer_is_not_cached(self, post):
        post.return_value = mock.Mock(status_code=200, json=lambda: {"verdict": "clean", "mode": "fast"})
        ipcheck.check("192.0.2.3")
        self.assertIsNone(cache.get("iplogs:192.0.2.3"))

    def test_should_block(self):
        self.assertTrue(ipcheck.should_block({"verdict": "vpn_detected"}))
        self.assertTrue(ipcheck.should_block({"verdict": "vpn_likely", "is_proxy": True}))
        self.assertFalse(ipcheck.should_block({"verdict": "suspicious", "is_proxy": True, "is_relay": True}))
        self.assertFalse(ipcheck.should_block({"verdict": "vpn_detected", "is_relay": True}))  # WARP
        self.assertFalse(ipcheck.should_block(None))

manage.py shell -c is enough for a live check. The address below was a published Tor exit relay when this ran on 27 October 2026:

$ python manage.py shell -c "from accounts import ipcheck; v = ipcheck.check('192.42.116.44'); print(v['verdict'], v['score'], v['is_vpn'], v['is_proxy'], v['ip_info']['vpn_provider'])"
vpn_detected 1 True True Tor

Django's test client sends requests with REMOTE_ADDR set to 127.0.0.1. Loopback is in the trusted list above, so self.client.post(url, HTTP_X_FORWARDED_FOR="192.42.116.44") behaves like a visitor arriving through your proxy. It works only because loopback is trusted; with any other REMOTE_ADDR, client_ip() ignores the header.

Questions people also ask

Does Django have built-in VPN or proxy detection?

No, and it doesn't parse X-Forwarded-For either: the middleware that did was removed in Django 1.1 as unreliable. You get REMOTE_ADDR, and classifying that address as a VPN, proxy or Tor exit takes an external API or dataset.

Is it safe to use the first IP in X-Forwarded-For?

No. The client writes that entry, so it can say anything. Take the rightmost entry that isn't one of your proxies, and read the header at all only when REMOTE_ADDR is one of them.

Which cache backend should the VPN check use?

One that's shared between processes. The default LocMemCache keeps a separate cache in each worker, so the same IP can be looked up once per worker. Django's built-in RedisCache backend shares verdicts across workers and servers.

Why does my DRF permission say "Authentication credentials were not provided"?

It returned False for a request with no authenticated user, and DRF reports that as NotAuthenticated. Raise PermissionDenied with your own message inside has_permission() instead.

Sources

  1. Django 6.1 docs: Request and response objects (HttpRequest.META, resolver_match)
  2. Django 6.1 docs: Middleware (writing middleware, process_view)
  3. Django 6.1 docs: Django's cache framework
  4. Django 6.1 docs: django.urls utility functions (ResolverMatch)
  5. Django 1.1 release notes: Removed SetRemoteAddrFromForwardedFor middleware
  6. Django REST framework: Permissions
  7. Django REST framework: Requests (standard HttpRequest attributes)
  8. Django REST framework: Throttling (NUM_PROXIES)
  9. Requests docs: Quickstart, Timeouts
  10. Requests docs: Advanced usage, Timeouts
  11. HTTPX docs: Timeouts
  12. Cloudflare docs: Cloudflare HTTP headers