pip3 install Flask-WTF
then in code
from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect()
csrf.init_app(app)
and inside templates (in forms), just add this line:
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
Now, by default, all POST, PUT, PATCH, and DELETE methods are protected against CSRF. Take note of this. You should never perform a side effect, like changing data in the database, via a GET request.
As for the JSON APIs, limiting the allowed origins or eliminating CORS altogether is a great way to prevent unwanted requests. You don't need to use CSRF tokens in that situation. If you have a more open CORS policy with regard to origins, it's a good idea to use CSRF tokens.
← Back to Articles