我为每个帖子和 xhr 请求传递一个 csrf_token,并希望根据会话 csrf 令牌验证令牌。如果它们不匹配,我会抛出 401。
我已经使用金字塔中的 NewResponse 订阅者来检查请求并根据会话中的令牌验证请求参数中的 csrf 令牌。验证有效,但它仍然调用视图,因此它无法正常工作。
关于正确方法的任何建议?
@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 = []