Flask-WTF set time limit on CSRF token

2024/11/17 11:34:58

I'm currently using Flask-WTF v0.13.1, i have a few forms on my website, all created including the CSRF token.

For some reasons i have to set a different expiration on each form, so far i could set manually the time_limit value upon creating the csrf token.

I would like to update to the v0.14, according to the changelog time_limit is gone and there is no reference in the docs on how to change it anymore. Looking in the source code i saw that the form has a csrf_time_limit meta parameter.

I tried to set that parameter on my form:

from flask_wtf import FlaskFormclass myForm(FlaskForm):class Meta:csrf_time_limit = 7200content = TextAreaField('content')

Although debugging the csrf.py module i see that the validate_csrf_token of _FlaskFormCSRF is actually never called.

The method validate_csrf is called within the method protect() instead, in this case the meta parameter is never considered.

I don't understand if this is a bug of the package or if i'm missing something.

UPDATE:

Example code:

app.py

from flask import Flask, render_template, request
from flask_wtf.csrf import CSRFProtect
from flask_wtf import FlaskForm
from wtforms import IntegerFieldcsrf = CSRFProtect()
app = Flask(__name__)
app.config.update(dict(SECRET_KEY="super secret key"
))csrf.init_app(app)class MyForm(FlaskForm):class Meta:csrf_time_limit = 1id = IntegerField('id')@app.route("/", methods=['GET', 'POST'])
def test_form_csrf():if request.method == 'POST':myForm = MyForm(request.form)print(myForm.id.data)return render_template('test_form.html', myForm= MyForm())

templates/test_form.html

<form method="post" action="/"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />{{ myForm.id }}<input type="submit" value="test" />
</form>

requirements.txt

click==6.7
Flask==0.12.2
Flask-WTF==0.14.2
itsdangerous==0.24
Jinja2==2.10
MarkupSafe==1.0
Werkzeug==0.14.1
WTForms==2.1

project structure

app.py
templates
|
--- test_form.html

To run the code,

FLASK_APP=app.py flask run

I also put a debug breakpoint on this line to check the actual value of time_limit, the value is always 3600.

Answer

Following your changelog link, I looked through the commit and found these lines:

if time_limit is None:time_limit = current_app.config.get('WTF_CSRF_TIME_LIMIT', 3600)

Setting app.config['WTF_CSRF_TIME_LIMIT'] to some shorter value seems to work. I have set it to 30 seconds with app.config['WTF_CSRF_TIME_LIMIT'] = 30 and the form expired after that amount of time, but I have not tried a longer value than the default.

I am not sure if you can change an app.config value on the fly in order to hack your way around not being able to set an expiration per form.

https://en.xdnf.cn/q/71226.html

Related Q&A

Extracting Intermediate layer outputs of a CNN in PyTorch

I am using a Resnet18 model. ResNet((conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)(bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats…

In Tensorflow, how to unravel the flattened indices obtained by tf.nn.max_pool_with_argmax?

I meet a problem: After I use the tf.nn.max_pool_with_argmax, I obtain the indices i.e. argmax: A Tensor of type Targmax. 4-D. The flattened indices of the max values chosen for each output.How to unr…

How write csv file without new line character in last line?

I have a code like this to write csv file in python import csv with open(eggs.csv, wb) as csvfile:spamwriter = csv.writer(csvfile, delimiter= ,quotechar=|, quoting=csv.QUOTE_MINIMAL)spamwriter.writerow…

Getting tests to parallelize using nose in python

I have a directory with lots of .py files (say test_1.py, test_2.py and so on) Each one of them is written properly to be used with nose. So when I run nosetests script, it finds all the tests in all t…

Python IDLE is not starting on Windows 7

I used to use Python 2.7 and then IDLE was working. I uninstalled it and installed Python 3.1. Right now Idle cannot launch. What should i do to get it running?NOTE: I tried c:\Python31\pythonw.exe c:…

SocketIO + Flask Detect Disconnect

I had a different question here, but realized it simplifies to this: How do you detect when a client disconnects (closes their page or clicks a link) from a page (in other words, the socket connection …

Numpy Array Broadcasting with different dimensions

I a little confused by the broadcasting rules of numpy. Suppose you want to perform an axis-wise scalar product of a higher dimension array to reduce the array dimension by one (basically to perform a …

xml filtering with python

I have a following xml document:<node0><node1><node2 a1="x1"> ... </node2><node2 a1="x2"> ... </node2><node2 a1="x1"> ... </no…

What it really is @client.event? discord.py

A few days ago I became interested in programming discord bots a bit. In the syntax of these programs I noticed a lot of unintelligible issues that I can not find an answer to. Thats why I am asking y…

How to customize virtualenv shell prompt

How do you define a custom prompt to use when activating a Python virtual environment?I have a bash script for activating a virtualenv I use when calling specific Fabric commands. I want the shell pro…