Skip to content
Closed
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
8 changes: 8 additions & 0 deletions docs/changes.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
Changes
=======

Version 1.3.1
-------------

Unreleased

- Nested blueprints inherit CSRF exemption from an exempt parent.
:issue:`697`

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

Expand Down
2 changes: 2 additions & 0 deletions docs/csrf.rst
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,8 @@ You can exclude all the views of a blueprint. ::

csrf.exempt(account_blueprint)

If that blueprint has nested children, they are exempt as well.

You can disable CSRF protection in all views by default, by setting
``WTF_CSRF_CHECK_DEFAULT`` to ``False``, and selectively call
:meth:`~flask_wtf.csrf.CSRFProtect.protect` only when you need. This also enables you to do some
Expand Down
17 changes: 15 additions & 2 deletions src/flask_wtf/csrf.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,8 +300,17 @@ def protect(self, apply_exemptions=False):
g.csrf_valid = True # mark this request as CSRF valid

def _is_exempt(self):
if current_app.blueprints.get(request.blueprint) in self._exempt_blueprints:
return True
bp_name = request.blueprint
if bp_name:
# Nested blueprints use dotted names (parent.child). Exempting a
# parent should also skip CSRF on its children.
name = bp_name
while True:
if current_app.blueprints.get(name) in self._exempt_blueprints:
return True
if "." not in name:
break
name = name.rsplit(".", 1)[0]

view = current_app.view_functions.get(request.endpoint)
if view is None:
Expand All @@ -325,6 +334,10 @@ def some_view():
bp = Blueprint(...)
csrf.exempt(bp)

Nested blueprints inherit exemption from a parent passed here.

.. versionchanged:: 1.3.1
Exempting a parent blueprint also exempts nested child blueprints.
"""

if isinstance(view, Blueprint):
Expand Down
16 changes: 16 additions & 0 deletions tests/test_csrf_extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,22 @@ def index():
assert response.status_code == 200


def test_exempt_parent_covers_nested_blueprint(app, csrf, client):
parent = Blueprint("api", __name__, url_prefix="/api")
child = Blueprint("meta", __name__, url_prefix="/meta")
csrf.exempt(parent)

@child.route("/", methods=["POST"])
def index():
return "ok"

parent.register_blueprint(child)
app.register_blueprint(parent)

response = client.post("/api/meta/")
assert response.status_code == 200


def test_error_handler(app, client):
@app.errorhandler(CSRFError)
def handle_csrf_error(e):
Expand Down
Loading