Flask Preventing Form Injection Flask Preventing Form Injection flask flask

Flask Preventing Form Injection


app.py

from flask import Flask, request, render templatefrom flask_wtf.csrf import CSRFProtectapp = Flask(__name__)CSRFProtect(app)app.config['SECRET_KEY'] = 'somethignrandom'@app.route('/', methods=['GET','POST'])def helloworld():    if request.method == 'GET':        return render_template('index.html')     if request.method == 'POST': # anything post will autocheck csrf        print(request.form['info'])        ## do something with the info, like write to a database        return 'nothing'if __name__ == '__main__':    app.run(debug=True)

There is no need to pass the secret key to the html template, as CSRFProtect will automatically pass the secret key.

templates/index.html

<html><head><script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><meta name='csrf-token' content="{{ csrf_token() }}"><script type='text/javascript' src="{{ url_for('static', filename='js/fire.js') }}"></script></head><body><p>Hello world!</p></body></html>

script.js

$(document).click(function() {    // post data to flask    $.post('/', {'info': 'test', '_csrf_token':$('meta[name="csrf-token"]').attr('content')});    return false;};