如何将csrf验证添加到金字塔中?

2024-10-05 17:44:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我为每个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 = []

Tags: orandthetokeneventgetisresponse
2条回答

在调用您的视图之后,NewResponse订户被调用。在

您希望使用之前调用的事件,例如NewRequest或{}。在Pyramid1.0中,您需要使用ContextFound来正确处理事情,因为您不能在NewRequest事件中引发异常(这在1.1中已修复)。在

使用ContextFound事件的方法是为HTTPException对象注册一个异常视图,如下所示:

config.add_view(lambda ctx, req: ctx, 'pyramid.httpexceptions.HTTPException')

基本上,当您引发异常时,它将作为响应对象返回异常,这对于HTTPException对象是有效的PyramidResponse对象是完全有效的。在

然后,您可以注册您的活动并处理CSRF验证:

^{pr2}$

金字塔包含它的own CSRF validation,这可能是一个更好的选择。在

给定会话存储的CSRF令牌,这将导致以下配置:

from pyramid.csrf import SessionCSRFStoragePolicy

def includeme(config):
    # ...
    config.set_csrf_storage_policy(SessionCSRFStoragePolicy())
    config.set_default_csrf_options(require_csrf=True)

相关问题 更多 >