I have a single page webapp that I am writing that will take a user name and api key and will do REST full API calls. Since the user uses a apikey for their account, there is no need to log in. I am not using cookies ether.
On the backend, I am using a simple flask server. The front end is a custom written without a framework using mostly html and vanilla JavaScript. I am not sure how to implement CSRF protection without using a framework. I could use Javascript to dynamically generate a token and place it in the html form field as a hidden element. But I don't know how I would get that token to the flask server so it could have it to compare. Without using a template engine, how could I do this?
First you need to generate csrf token from server and client can get it through a simple request, then pass it back in post request. You can use below method to generate token.
flask_wtf.csrf.generate_csrf(secret_key=None, time_limit=None)
For example,
@app.route('/token')
def token():
token=generate_csrf(time_limit=10)
return jsonify({'token':token}), 201
Then post request with header 'X-CSRFToken'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With