简体   繁体   English

如何对单页应用程序使用Flask-WTF CSRF保护?

[英]How to use Flask-WTF CSRF protection for Single Page Apps?

I noticed that tokens generated by Flask-WTF expire in one hour and a different one is generated every request. 我注意到Flask-WTF生成的令牌在一小时内到期,并且每个请求都会生成一个不同的令牌。 This will cause problems in SPAs when a page has been opened longer than an hour. 当页面打开时间超过一个小时时,这将在SPA中引起问题。 XHR requests made after one hour after page-load will start failing, even if the user was active. 页面加载一小时后发出的XHR请求将开始失败,即使用户处于活动状态也是如此。

My workaround is to set a new token in the browser in each API call. 我的解决方法是在每个API调用的浏览器中设置一个新令牌。 In the server, all API responses contain a freshly-generated token: 在服务器中,所有API响应都包含一个新生成的令牌:

from flask_wtf.csrf import generate_csrf

def api_response(data, error=None):
    response = {"csrftoken": generate_csrf(), "data":data}
    ...
    return make_response(jsonify(response), response_code)

In the browser we set the csrftoken on each API response. 在浏览器中,我们在每个API响应上设置csrftoken。

then(function(result) {
    if(result.csrftoken) csrftoken=result.csrftoken;
    callback(result);
  })

Is this method still safe and fast? 这种方法仍然安全快捷吗? Is there a better way to handle this? 有没有更好的方法来解决这个问题? I am not too sure about using generate_csrf directly. 我不太确定直接使用generate_csrf。

No, there is no other way to use the CSRF protection in Flask-WTF. 不,没有其他方法可以在Flask-WTF中使用CSRF保护。 When you need a CSRF token, you need to generate one and use it. 当需要CSRF令牌时,需要生成一个令牌并使用它。 There should be no problem with generating it like you do. 像您一样生成它应该没有问题。 It is still generated and validated the same way on the server, and transmitted over the same channel to the client. 它仍然在服务器上以相同的方式生成和验证,并通过相同的通道传输到客户端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM