我为每个post和xhr请求传递一个csrf_令牌,并希望根据会话csrf令牌验证令牌。如果他们不匹配,我投401。在
我使用金字塔中的NewResponse订户检查请求,并根据会话中的令牌验证请求参数中的csrf令牌。验证可以工作,但它仍然调用视图,因此它def不能正常工作。在
有什么建议吗?在
@subscriber(NewResponse)
def new_response(event):
"""Check the csrf_token if the user is authenticated and the
request is a post or xhr req.
"""
request = event.request
response = event.response
user = getattr(request, 'user', None)
# For now all xhr request are csrf protected.
if (user and user.is_authenticated()) and \
(request.method == "POST" or request.is_xhr) and \
(not request.params.get('csrf_token') or \
request.params.get('csrf_token') != unicode(request.session.get_csrf_token())):
response.status = '401 Unauthorized'
response.app_iter = []
在调用您的视图之后,
NewResponse
订户被调用。在您希望使用之前调用的事件,例如}。在Pyramid1.0中,您需要使用
NewRequest
或{ContextFound
来正确处理事情,因为您不能在NewRequest
事件中引发异常(这在1.1中已修复)。在使用
ContextFound
事件的方法是为HTTPException对象注册一个异常视图,如下所示:基本上,当您引发异常时,它将作为响应对象返回异常,这对于HTTPException对象是有效的Pyramid
Response
对象是完全有效的。在然后,您可以注册您的活动并处理CSRF验证:
^{pr2}$金字塔包含它的own CSRF validation,这可能是一个更好的选择。在
给定会话存储的CSRF令牌,这将导致以下配置:
相关问题 更多 >
编程相关推荐