CSRF protection without using Engine-Javascript and Flask pattern

I have a one-page webapp that I am writing that will use the username and api key and will make all REST API calls. Since the user uses apikey for his account, there is no need to log in. I do not use a cookie.

On the backend, I use a simple flask server. The front end is a custom written without a frame using mostly html and vanilla JavaScript. I'm not sure how to implement CSRF protection without using a framework. I could use Javascript to dynamically create the token and put it in the html form field as a hidden element. But I do not know how I will get this token on the flask server so that it can compare it. Without using the template engine, how could I do this?

+3
source share
1 answer

First you need to generate the csrf token from the server, and the client can get it through a simple request, and then pass it back in the mail request. You can use the method below to create a token.

flask_wtf.csrf.generate_csrf(secret_key=None, time_limit=None)

For instance,

@app.route('/token')

def token():

    token=generate_csrf(time_limit=10)

    return jsonify({'token':token}), 201

Then send a request with a heading 'X-CSRFToken'

+1
source

All Articles