首页 > 解决方案 > 使用 HTTPS 应用程序负载均衡器时 Django Fargate Docker 中的 CSRF 错误

问题描述

我在 AWS Fargate 上使用应用程序负载均衡器后面的 Docker 实现了一个 Django Web 应用程序。

当我尝试登录网络应用程序时,我得到以下信息:

错误 403 CSRF verification failed. Request aborted.

环境:我正在按照 AWS 的最佳实践使用 Application Load Balancer (ALB)。当我运行 Web 应用程序的多个实例时,ALB 还具有 TLS 证书以正确处理 HTTPS。

我试图通过强制 ALB 目标的粘性来解决这个问题,假设循环将请求放在不同的服务器上。我还将 docker 实例的数量减少到一个(因此没有循环)。

这些都没有任何区别。

当我直接连接到 docker 实例(无负载均衡器)并且在应用程序负载均衡器上仅使用 HTTP 时,我设法登录(以使 CSRF 正常工作) - 禁用重定向到 HTTPS。这让我相信问题出在负载均衡器的 HTTPS 部分和 Django Web 应用程序之间。

禁用 HTTPS 还没有准备好生产,所以我回到了第一方。我在这里看到了一个类似的问题,没有答案: django posts receive CSRF verification failed after switch to load balancer

标签: djangoamazon-web-servicesdocker

解决方案


在对实时系统进行调试作为临时措施后,潜在的问题变得清晰起来。

引用者检查失败 - https://test.domain.tld/path/不匹配任何受信任的来源。

解决方案是通过 Django 中的 CSRF_TRUSTED_ORIGINS 参数。来自 Django 文档的引用:

    CSRF_TRUSTED_ORIGINS
    Default: [] (Empty list)
    
    A list of hosts which are trusted origins for unsafe requests (e.g. POST). 
For a secure unsafe request, Django’s CSRF protection requires that the request have a Referer header that matches the origin present in the Host header. 
This prevents, for example, a POST request from subdomain.example.com from succeeding against api.example.com. 
If you need cross-origin unsafe requests over HTTPS, continuing the example, add "subdomain.example.com" to this list. 
The setting also supports subdomains, so you could add ".example.com", for example, to allow access from all subdomains of example.com.

在此线程中可以找到类似的讨论和解决方案。 CSRF 验证在使用 HTTPS 的 Django 上不起作用


推荐阅读