Flask-Restful POST由于Flask-WTF的CSRF保护而失败 [英] Flask-Restful POST fails due CSRF protection of Flask-WTF
问题描述
我使用的是普通烧瓶瓶+烧瓶瓶固定式.因此,我需要针对Web的CSRF保护,而不需要针对REST.
I am using normal flask web + flask-restful. So I need CSRF protection for web but not for REST.
当我启用flask-wtf
的CsrfProtect(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)
推荐答案
您可以使用 decorators
参数;这会将装饰器应用于所有 API路由:
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屋!