对 Django 的请求中缺少自定义 headers

Custom headers missing in requests to Django

上下文:我编写了一个 Django 应用程序,现在已将其部署到 Elastic Beanstalk (AWS)。

在本地开发中,我一直在使用自定义请求 header SESSION_TOKEN,然后我可以使用 request.META.get('HTTP_SESSION_TOKEN') 访问它。在生产中我看到错误,因为 header 不可访问(也就是我的 Django 服务器看到的所有请求中都缺少它)。

此外,我的其他标准 header 工作正常,只是缺少自定义 header。注意我没有设置 HTTP_AUTHORIZATION,这与 Authorization header missing in django rest_framework, is apache to blame?.

不是同一个问题

出了什么问题?如何在我的生产后端访问自定义 header?

很可能 SESSION_TOKEN header 被什么东西剥夺了。来自 Django security advisory:

When HTTP headers are placed into the WSGI environ, they are normalized by converting to uppercase, converting all dashes to underscores, and prepending HTTP_. For instance, a header X-Auth-User would become HTTP_X_AUTH_USER in the WSGI environ (and thus also in Django's request.META dictionary).

Unfortunately, this means that the WSGI environ cannot distinguish between headers containing dashes and headers containing underscores: X-Auth-User and X-Auth_User both become HTTP_X_AUTH_USER. This means that if a header is used in a security-sensitive way (for instance, passing authentication information along from a front-end proxy), even if the proxy carefully strips any incoming value for X-Auth-User, an attacker may be able to provide an X-Auth_User header (with underscore) and bypass this protection.

最重要的信息:

In order to prevent such attacks, both Nginx and Apache 2.4+ strip all headers containing underscores from incoming requests by default. Django's built-in development server now does the same. Django's development server is not recommended for production use, but matching the behavior of common production servers reduces the surface area for behavior changes during deployment.

如果您有任何自定义 header,您应该改用连字符。