Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Respect exempts in CSRFProtect.protect() #419

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
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
21 changes: 10 additions & 11 deletions flask_wtf/csrf.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,16 +213,7 @@ def csrf_protect():
if not request.endpoint:
return

if request.blueprint in self._exempt_blueprints:
return

view = app.view_functions.get(request.endpoint)
dest = f'{view.__module__}.{view.__name__}'

if dest in self._exempt_views:
return

self.protect()
self.protect(respect_exempts=True)

def _get_csrf_token(self):
# find the token in the form data
Expand All @@ -249,7 +240,15 @@ def _get_csrf_token(self):

return None

def protect(self):
def protect(self, respect_exempts=False):
if respect_exempts:
if request.blueprint in self._exempt_blueprints:
return

view = current_app.view_functions.get(request.endpoint)
if view is not None and f'{view.__module__}.{view.__name__}' in self._exempt_views:
return

if request.method not in current_app.config['WTF_CSRF_METHODS']:
return

Expand Down
12 changes: 12 additions & 0 deletions tests/test_csrf_extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,18 @@ def manual():
assert response.status_code == 400


def test_exempt_with_manual_protect(app, csrf, client):
app.config['WTF_CSRF_CHECK_DEFAULT'] = False

@app.route('/manual', methods=['POST'])
@csrf.exempt
def manual():
csrf.protect(respect_exempts=True)

response = client.post('/manual')
assert response.status_code == 200


def test_exempt_blueprint(app, csrf, client):
bp = Blueprint('exempt', __name__, url_prefix='/exempt')
csrf.exempt(bp)
Expand Down