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

Allow disabling CSRF based on request context #495

Open
hMED22 opened this issue Dec 22, 2021 · 1 comment
Open

Allow disabling CSRF based on request context #495

hMED22 opened this issue Dec 22, 2021 · 1 comment
Labels

Comments

@hMED22
Copy link

hMED22 commented Dec 22, 2021

Instead of CSRFProtect.exempt that disables CSRF on a view for all requests, there should also be a way to disable it for all views based on the request context, like token authenticated requests for example.

For this the docs suggest

setting WTF_CSRF_CHECK_DEFAULT to False, and selectively call protect() only when you need.

But it doesn't feel right to disable the extension globally, plus that way CSRFProtect.exempt is no longer usable.

I tried something like

@app.before_request
def _disable_csrf_for_token_auth():
    if token_authenticated(request):
        g.csrf_valid = True

But CSRF protection runs and returns an error response before my hook gets called.

I am now going with a subclass:

class AuthAwareCSRFProtect(CSRFProtect):
    def protect(self):
        if token_authenticated(request):
            g.csrf_valid = True
            return

        return super().protect()

One problem of this is that g.csrf_valid is internal to flask-wtf and not documented as part of the API so I don't know if it's a good idea to use it.

@hMED22 hMED22 changed the title Allow disabling CSRF Allow disabling CSRF based on request context Dec 22, 2021
@azmeuk azmeuk added the csrf label Jul 25, 2023
@fiendish
Copy link

fiendish commented May 31, 2024

I also desire to transiently disable CSRF for a single request based on the request context.

One problem of this is that g.csrf_valid is internal to flask-wtf and not documented as part of the API so I don't know if it's a good idea to use it.

Likewise. An ok fix for this could be to just call it official and document it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

No branches or pull requests

3 participants