微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何将CSRF验证添加到金字塔?

| 我正在为每个post和xhr请求传递一个csrf_token,并希望针对会话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 = []
    

解决方法

        调用视图后,将调用“ 1”订户。 您要使用一个先前调用的事件,例如
NewRequest
ContextFound
。在Pyramid 1.0中,您将需要使用
ContextFound
来正确处理事情,因为您无法在
NewRequest
事件中引发异常(此问题已在1.1中修复)。 使用
ContextFound
事件执行此操作的方法是为HTTPException对象注册异常视图,如下所示:
config.add_view(lambda ctx,req: ctx,\'pyramid.httpexceptions.HTTPException\')
基本上,这将在引发异常时将异常作为响应对象返回,这对于有效的Pyramid
Response
对象的HTTPException对象是完全有效的。 然后,您可以注册事件并进行CSRF验证:
@subscriber(ContextFound)
def csrf_validation_event(event):
    request = event.request
    user = getattr(request,\'user\',None)
    csrf = request.params.get(\'csrf_token\')
    if (request.method == \'POST\' or request.is_xhr) and \\
       (user and user.is_authenticated()) and \\
       (csrf != unicode(request.session.get_csrf_token())):
        raise HTTPUnauthorized
    ,        金字塔包含其自己的CSRF验证,这可能是一个更好的选择。 给定您的会话存储的CSRF令牌,这将导致以下配置:
from pyramid.csrf import SessionCSRFStoragePolicy

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。