Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/changes.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
Changes
=======

- Allow configuration of the CSRF token signer using ``WTF_CSRF_SIGNER`` and
``WTF_CSRF_SIGNER_KWARGS``

Version 1.3.0
-------------

Expand Down
6 changes: 6 additions & 0 deletions docs/config.rst
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,15 @@ Configuration
Also set to ``False`` if you want to use WTForms's
built-in messages directly, see more info `here`_.
Default is ``True``.
``WTF_CSRF_SIGNER`` Set to a subclass of the `Signer`_ class to use
custom token-signing behavior. Default is the default
for the ``itsdangerous`` library.
``WTF_CSRF_SIGNER_KWARGS`` Controls the kwargs passed to the Signer class.
Default is ``None``.
========================== =====================================================

.. _here: https://wtforms.readthedocs.io/en/stable/i18n.html#using-the-built-in-translations-provider
.. _Signer: https://itsdangerous.palletsprojects.com/en/stable/signer/

Recaptcha
---------
Expand Down
23 changes: 21 additions & 2 deletions src/flask_wtf/csrf.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def generate_csrf(secret_key=None, token_key=None):
)

if field_name not in g:
s = URLSafeTimedSerializer(secret_key, salt="wtf-csrf-token")
s = _get_serializer(secret_key)

if field_name not in session:
session[field_name] = hashlib.sha1(os.urandom(64)).hexdigest()
Expand Down Expand Up @@ -104,7 +104,7 @@ def validate_csrf(data, secret_key=None, time_limit=None, token_key=None):
if field_name not in session:
raise ValidationError("The CSRF session token is missing.")

s = URLSafeTimedSerializer(secret_key, salt="wtf-csrf-token")
s = _get_serializer(secret_key)

try:
token = s.loads(data, max_age=time_limit)
Expand Down Expand Up @@ -159,6 +159,23 @@ def _get_config(
return value


def _get_serializer(secret_key):
"""Create and return a Serializer to be used for CSRF tokens.

:param secret_key: secret key used to sign the token
"""
kwargs = {
"salt": "wtf-csrf-token",
}
if "WTF_CSRF_SIGNER" in current_app.config:
kwargs["signer"] = current_app.config["WTF_CSRF_SIGNER"]

if "WTF_CSRF_SIGNER_KWARGS" in current_app.config:
kwargs["signer_kwargs"] = current_app.config["WTF_CSRF_SIGNER_KWARGS"]

return URLSafeTimedSerializer(secret_key, **kwargs)


class _FlaskFormCSRF(CSRF):
def setup_form(self, form):
self.meta = form.meta
Expand Down Expand Up @@ -221,6 +238,8 @@ def init_app(self, app):
app.config.setdefault("WTF_CSRF_META_NAME", "csrf-token")
app.config.setdefault("WTF_CSRF_TIME_LIMIT", 3600)
app.config.setdefault("WTF_CSRF_SSL_STRICT", True)
app.config.setdefault("WTF_CSRF_SIGNER", None)
app.config.setdefault("WTF_CSRF_SIGNER_KWARGS", None)

app.jinja_env.globals["csrf_token"] = generate_csrf
app.jinja_env.globals["csrf_meta_tag"] = csrf_meta_tag
Expand Down
18 changes: 18 additions & 0 deletions tests/test_csrf_extension.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import hashlib

import pytest
from flask import Blueprint
from flask import g
Expand Down Expand Up @@ -269,3 +271,19 @@ def assert_info(message):
client.post("/")
assert len(messages) == 1
assert messages[0] == "The CSRF token is missing."


def test_csrf_signer_config(app, req_ctx):
from itsdangerous.signer import Signer

class TestSigner(Signer):
def sign(self, value):
return super().sign(value) + b"-test"

app.config["WTF_CSRF_SIGNER"] = TestSigner
assert generate_csrf().endswith("-test")


def test_csrf_signer_kwargs_config(app, req_ctx):
app.config["WTF_CSRF_SIGNER_KWARGS"] = {"digest_method": hashlib.sha256}
assert len(generate_csrf()) == 107
Loading