Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSRF Protection without using template Engine- Javascript and Flask

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?

like image 628
dman Avatar asked Mar 15 '26 07:03

dman


1 Answers

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'

like image 130
Xiaokun Avatar answered Mar 16 '26 19:03

Xiaokun