Search code examples
htmlpython-3.xflaskcsrf-token

How to add csrf to flask app without wtforms?


I have a simple web app, And I want to add csrf protection. But I didn’t understand the csrf wrapper provided by Flask-WTF. I've already seen the docs. But still didn’t understand how it works.

My questions is:

(1) After wrapping the app, Do I need to handle it from the route? Or flask take care of that for me?

(2) If Not how to handle it myself? (Please provide an example).

Note: I Don't want to use wtf forms, I wanted to use custom tags for inputs.

app.py :

from flask import Flask, render_template
from flask_wtf.csrf import CSRFProtect

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
csrf = CSRFProtect(app)

@app.route('/', methods=['GET'])
def get_home():
    """Get home template"""
    return render_template('home.html')

@app.route('/', methods=['POST'])
def post_home():
    """Handle posted data and do stuff"""
    return

home.html (form):

<form action="#" method="post">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
    <input type="text" placeholder="Name">
    <button type="submit">
        Submit
    </button>
</form>

Solution

  • By default, you don't need to worry about validating it yourself - you simply deal with the other fields of the POST request as normal. If you look at the function csrf_protect() within the init_app function of the CSRFProtect class here (lines 202-225, https://github.com/lepture/flask-wtf/blob/master/flask_wtf/csrf.py), you can view the things which will stop the protect() function being run before a given request.