Complete worked example
python
from flask import Flask, request, session
from flask_wtf.csrf import CSRFProtect, generate_csrf
def csrf_request(mode):
app = Flask(__name__)
app.config.update(TESTING=True, SECRET_KEY='owned-csrf-key')
CSRFProtect(app)
@app.get('/token')
def token():
return {'token': generate_csrf()}
@app.post('/save')
def save():
return {'saved': True}, 201
client = app.test_client()
token = client.get('/token').json['token']
headers = {'X-CSRFToken': token} if mode == 'correct' else {}
if mode == 'wrong':
headers['X-CSRFToken'] = 'invalid-owned-fixture'
return client.post('/save', headers=headers).status_code- Reasoning
- The owned client first retrieves generate_csrf output, retaining the corresponding session cookie. It then posts the token through the extension’s recognized X-CSRFToken header.