Flask-Restful POST由于Flask-WTF的CSRF保护而失败 [英] Flask-Restful POST fails due CSRF protection of Flask-WTF

查看:154
本文介绍了Flask-Restful POST由于Flask-WTF的CSRF保护而失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是普通烧瓶瓶+烧瓶瓶固定式.因此,我需要针对Web的CSRF保护,而不需要针对REST.

I am using normal flask web + flask-restful. So I need CSRF protection for web but not for REST.

当我启用flask-wtfCsrfProtect(app)时,我对flask-restful的所有后期单元测试都会返回400.

The moment I enable CsrfProtect(app) of flask-wtf, all my post unit tests for flask-restful return a 400.

是否有一种方法可以禁用针对REST服务的CSRF保护,因为它们来自手机,无论如何它们都没有会话处理,因此CSRF毫无意义.

Is there a way to disable CSRF protection for REST services since they are coming from mobile handsets without session handling anyway, hence CSRF wouldn't make much sense.

这是我的测试方式:

rv = self.client.post('api/v1.0/verify-email', environ_base={'REMOTE_ADDR': '127.0.0.1'}, headers={'Content-Type':'application/json'}, data=json.dumps(data))
self.check_content_type(rv.headers)
eq_(rv.status_code, 412)

推荐答案

您可以使用

You can use the @csrf.exempt decorator, which you need to add directly on the API object, with the decorators argument; this would apply the decorator to all API routes:

csrf_protect = CsrfProtect(app)
api = restful.Api(app, decorators=[csrf_protect.exempt])

您不能使用资源方法修饰符因为它们不是exempt装饰器需要工作的最终视图函数.

You cannot use resource method decorators as they are not the final view functions that the exempt decorator requires to work.

看来您无法保护个人资源而不能豁免他人;这是Flask-Wtf记录哪些视图被豁免的方法所使用的方法的局限性.

It appears you cannot protect individual resources and exempt others; this is a limitation in the method used by Flask-Wtf's method of recording what views are exempted.

这篇关于Flask-Restful POST由于Flask-WTF的CSRF保护而失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆