django:不为特定端点返回cookie

时间:2019-04-11 08:43:37

标签: django cookies django-views

我需要返回Django的响应而不返回cookie。

我正在尝试实现一个要求的Webhook客户端API:

  • 使用https
  • 在5秒钟内回复
  • 没有人回应
  • 响应标题中没有cookie
  • 无效的hmac签名的401未经授权状态代码

我正在开发Django 1.10(很快将升级到2.x),该应用程序的其余部分受用户通过会话验证的保护。

部分端点视图如下:

response200 = HttpResponse(status=200)
response401 = HttpResponse(status=401)
response401.close()  # attempt not to set cookie

signature = request.META.get('HTTP_WEBHOOK_SIGNATURE')

if not request.method == 'POST':
    return response401
if not signature:
    return response401

以此类推。

但是,我尝试避免使用response401.close()设置会话的尝试无效。我也尝试过del response401['Set-Cookie'] see Django docs

此卷曲会话中仍设置了Cookie LocalTest...

$ curl -d "param1=value1&param2=value2" \
       -H "webhook-signature: $SIGVAL" \
       -H "Content-Type: application/x-www-form-urlencoded" \
       -X POST http://127.0.0.1:8000/invoices/webhookendpoint \
       -w "\n" -v
...
* Connected to 127.0.0.1 (127.0.0.1) port 8000 (#0)
> POST /invoices/webhookendpoint HTTP/1.1
> Host: 127.0.0.1:8000
> User-Agent: curl/7.52.1
> Accept: */*
> x-xero-signature: ZSlYlcsLbYmas53uHNrBFiVL0bLbIKetQI6x8JausfA=n
> Content-Type: application/x-www-form-urlencoded
> Content-Length: 27
> 
* upload completely sent off: 27 out of 27 bytes
* HTTP 1.0, assume close after body
< HTTP/1.0 401 Unauthorized
< Date: Thu, 11 Apr 2019 08:32:50 GMT
< Server: WSGIServer/0.1 Python/2.7.13
< Vary: Cookie
< Content-Type: text/html; charset=utf-8
< Set-Cookie:  LocalTest=gwx7jhsshy2qvtct1rmzv86h7xshe6ot; httponly; Path=/
< 
* Curl_http_done: called premature == 0
* Closing connection 0

1 个答案:

答案 0 :(得分:1)

似乎可行:

# ensure no cookie header is set
del request.session
response200 = HttpResponse(status=200)
response401 = HttpResponse(status=401)
...

如卷曲响应所示:

< HTTP/1.0 200 OK
< Date: Thu, 11 Apr 2019 08:49:28 GMT
< Server: WSGIServer/0.1 Python/2.7.13
< Content-Type: text/html; charset=utf-8
< 

自然,如果您以登录用户的身份转到该端点,则必须再次登录。