'How can I use Flask WTForms and CSRF without session cookie?

I have a very simple app that has no user management or any Flask-Login auth needs. It has forms, WTForms. All I want to do is collect some data submitted by the form. I could technically disable CSRF validation but Flask WTForms really urges me not to.

I'd like to disable flask session cookie in the browser because it seems unnecessary and I would need to put a cookie banner for GDPR compliance. So to avoid all that, I thought of disabling flask session cookie as follows:

class CustomSessionInterface(SecureCookieSessionInterface):
    """ Disable session cookies """
    def should_set_cookie(self, app: "Flask", session: SessionMixin) -> bool:
        return False

# App initialization
app = Flask(__name__)
app.session_interface = CustomSessionInterface()

But doing so leads to a 500 error: "The CSRF session token is missing". However, looking at the HTML that was rendered has the following csrf token rendered properly:

<input id="csrf_token" name="csrf_token" type="hidden" value="ImI2ZDIwMDUxMDNmOGM3ZDFlMTI4ZTIzODE4ODBmNDUwNWU3ZmMzM2Ui.YhA2kQ.UnIHwlR1qLL61N9_30lDKngxLlM">

Questions:

  1. What is the relationship between CSRF token validation and session cookie? Why is a cookie necessary to validated the CSRF token?
  2. I tried enabling session cookies again, deleting the cookie in Chrome developer tools leads to the same error. So, indeed, session cookie seems to be absolutely necessary to validate CSRF token.
  3. How can I use CSRF form validation without a session cookie?

Thank you so much.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source