Korzen's package for Python, korzen-bot-protection, serves both: a WSGI middleware for Flask and Django, and an ASGI one for Django under ASGI. It needs the standard library alone, asks /v1/decide, gives up at your timeout and lets the visitor through on any error.
Payment, login and sign-up routes: turn on protected_action=True, so a script that never loads your page cannot take the action. Protecting a checkout
The tag
Put the tag in the <head> of your base template (base.html), which the sign-up, sign-in and checkout pages extend:
<script src="https://eu.korzen.dev/v1/tag.js" data-site-key="YOUR_SITE_KEY" async></script>
For visitors whose network blocks Korzen's host, first_party=True serves the tag and its beacon from your own domain. First-party mode
The call
Behind Cloudflare? A Worker can do this without changing your app. Cloudflare Workers
Install the package from PyPI:
pip install korzen-bot-protection
In Flask, wrap the app in KorzenWSGI. On the paths you name, it asks before your view runs, answers a block itself, and leaves the answer in request.environ["korzen.decision"], or None when there is none:
# app.py import os from flask import Flask, redirect, render_template, request from korzen_bot_protection import Client, KorzenWSGI, last_forwarded_ip app = Flask(__name__) # One for the process. The timeout for your server's region: https://korzen.dev/bot-protection/docs/server-call#latency korzen = Client(os.environ["KORZEN_API_KEY"], url="https://eu.korzen.dev", timeout=0.2) def blocked(environ, start_response, decision): """A blocked sign-up gets the form's own error, so a bot learns nothing.""" start_response("400 Bad Request", [("Content-Type", "text/plain; charset=utf-8")]) return [b"We could not create your account."] app.wsgi_app = KorzenWSGI( app.wsgi_app, client=korzen, prefixes=["/signup"], ip=last_forwarded_ip, # one proxy of yours in front: see "The visitor's IP" protected_action=True, # sign-up, login and payment: a script that never loaded your page holds no token; a page load spends none on_block=blocked, ) @app.route("/signup", methods=["GET", "POST"]) def signup(): if request.method == "GET": return render_template("signup.html") d = request.environ["korzen.decision"] # a Decision, or None user = create_account(request.form) # your own code save_request_id(user, d and d.request_id) # see "Apply the action" return redirect("/welcome")
In Django, wrap the application in wsgi.py, or in asgi.py with KorzenASGI. The view finds the answer in request.META["korzen.decision"] under WSGI and in request.scope["korzen.decision"] under ASGI:
# wsgi.py import os from django.core.wsgi import get_wsgi_application from korzen_bot_protection import Client, KorzenWSGI, last_forwarded_ip os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") # The timeout for your server's region: https://korzen.dev/bot-protection/docs/server-call#latency korzen = Client(os.environ["KORZEN_API_KEY"], url="https://eu.korzen.dev", timeout=0.2) application = KorzenWSGI( get_wsgi_application(), client=korzen, prefixes=["/signup/"], ip=last_forwarded_ip, # one proxy of yours in front: see "The visitor's IP" protected_action=True, # a script that never loaded your page holds no token )
# views.py from django.shortcuts import redirect, render def signup(request): if request.method == "POST": d = request.META["korzen.decision"] # a Decision, or None user = create_account(request.POST) # your own code save_request_id(user, d and d.request_id) # see "Apply the action" return redirect("welcome") return render(request, "signup.html")
To ask inside a view instead, korzen.decide(from_wsgi(request.environ, ip=last_forwarded_ip, path="/signup")) returns the answer, or None on any error; it never raises. The package sends the request's headers in the order they came, as gunicorn keeps them in the WSGI environ; behind nginx, a load balancer or Cloudflare, that is the order the last hop forwards them in.
The visitor's IP
Without ip, the middleware takes the connection's address, your proxy's if you have one. Behind one proxy of yours (a load balancer, nginx) that appends to X-Forwarded-For, pass ip=last_forwarded_ip: it takes the entry that proxy added, not what the visitor wrote before it. With two proxies of yours, pass a function of your own that takes the entry before the last. Behind Cloudflare, pass ip=cloudflare_ip, which reads CF-Connecting-IP, if your server only takes traffic from Cloudflare.
Apply the action
The middleware applies action: on block it answers 403, or what your on_block returns, and your view never runs. Make that answer the error the form shows when it fails for any other reason, so a bot learns nothing. The account starts in monitor mode, where action is always allow: nothing changes for visitors until you turn on block mode.
Keep the answer's request_id with what the action created, such as the account or the order: it names that decision when you ask us about it. The answer
Test it on your machine
Run python manage.py runserver or flask run and open it on localhost. Pages on localhost always accept the tag and are never listed as a domain. Locally the IP is 127.0.0.1 or ::1, and that is fine. In Docker on your machine, the app sees the bridge's address instead, such as 172.17.0.1, and that is fine too.
- Set
KORZEN_API_KEYin the environment (or your.env, if you load one) and open the sign-up page. In the browser's developer tools, the_kzcookie appears after a few seconds. - Sign up. The decision shows on the dashboard's Decisions page, under the path you sent.
- Check fail open: set a wrong key and sign up again. The call answers
401, and the sign-up goes through.
Common mistakes
- The first entry of
X-Forwarded-For. The visitor writes it, so a bot picks its own IP. ip=last_forwarded_ipwith no proxy of yours in front. The visitor then writes the last entry too, and a bot picks its own IP.- A form posted by JavaScript as soon as the page loads, before the tag reported: call
await window.korzen?.ready()before you send it. - Calling
/v1/decidefrom the browser. The API key would reach every visitor; the call belongs on your server. - A line in your log that starts
korzen: the visitor's IP sent to Bot Protection. The client writes it once, at the first decision whose IP is your own network's (a load balancer's, a proxy's, a container's), which Bot Protection judges as no IP: setipto the visitor's address (the visitor's IP). In Docker on your machine it is the bridge's address, and harmless there.