[英]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. 我有一个单页webapp,我正在编写,它将采用用户名和api密钥,并将执行REST完整的API调用。 Since the user uses a apikey for their account, there is no need to log in. I am not using cookies ether.
由于用户为其帐户使用apikey,因此无需登录。我不使用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.
前端是一个没有框架的自定义编写,主要使用html和vanilla JavaScript。 I am not sure how to implement CSRF protection without using a framework.
我不确定如何在不使用框架的情况下实施CSRF保护。 I could use Javascript to dynamically generate a token and place it in the html form field as a hidden element.
我可以使用Javascript动态生成一个令牌,并将其作为隐藏元素放在html表单字段中。 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. 首先,您需要从服务器生成csrf令牌,客户端可以通过简单的请求获取它,然后在post请求中将其传回。 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'
然后使用标题
'X-CSRFToken'
发布请求
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.