Learn / Frameworks / Flask / CSRF, XSS and Hardening

Flask · Lesson 11 of 15

CSRF, XSS and Hardening

WTF CSRF, escaping, cookies, rate limits and HTTPS.

  • Advanced
  • 15 min read
  • 3 objectives

Before this lessonLesson 10: Testing Flask Apps

What you will learn

  • Turn on CSRF
  • Set secure cookies
  • Rate-limit login

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 4 hours

Create a free account to keep your progress on every device.

Flask does not turn on as many protections as Django by default. You opt in: CSRF, secure cookies, XSS-safe templates (already on), and rate limits.

CSRF with Flask-WTF

from flask_wtf import CSRFProtect
csrf = CSRFProtect()
csrf.init_app(app)
# In JSON APIs, send the X-CSRFToken header or exempt the blueprint:
# csrf.exempt(api)
<form method="post">{{ csrf_token() }} ... </form>

Cookies

app.config.update(
    SESSION_COOKIE_SECURE=True,
    SESSION_COOKIE_HTTPONLY=True,
    SESSION_COOKIE_SAMESITE="Lax",
    REMEMBER_COOKIE_SECURE=True,
)

Rate limiting

from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
limiter = Limiter(get_remote_address, app=app, default_limits=["200 per hour"])

@bp.route("/login", methods=["POST"])
@limiter.limit("5 per minute")
def login():
    ...
Up next · Lesson 12Caching and Background JobsFlask-Caching with Redis and a simple RQ worker for slow work.