diff --git a/django/middleware/csrf.py b/django/middleware/csrf.py index 835fee70a8..ca6c053339 100644 --- a/django/middleware/csrf.py +++ b/django/middleware/csrf.py @@ -174,7 +174,7 @@ class CsrfViewMiddleware(object): good_referer = request.get_host() else: good_referer = settings.CSRF_COOKIE_DOMAIN - server_port = request.META['SERVER_PORT'] + server_port = request.get_port() if server_port not in ('443', '80'): good_referer = '%s:%s' % (good_referer, server_port) diff --git a/docs/releases/1.9.2.txt b/docs/releases/1.9.2.txt index 9e13e705bc..71ca0dbea2 100644 --- a/docs/releases/1.9.2.txt +++ b/docs/releases/1.9.2.txt @@ -38,3 +38,6 @@ Bugfixes * Fixed a crash when destroying an existing test database on MySQL or PostgreSQL (:ticket:`26096`). + +* Fixed CSRF cookie check on POST requests when ``USE_X_FORWARDED_PORT=True`` + (:ticket:`26094`). diff --git a/tests/csrf_tests/tests.py b/tests/csrf_tests/tests.py index 987ecd31c5..54570dca42 100644 --- a/tests/csrf_tests/tests.py +++ b/tests/csrf_tests/tests.py @@ -375,6 +375,23 @@ class CsrfViewMiddlewareTest(SimpleTestCase): req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {}) self.assertIsNone(req2) + @override_settings(ALLOWED_HOSTS=['www.example.com'], CSRF_COOKIE_DOMAIN='.example.com', USE_X_FORWARDED_PORT=True) + def test_https_good_referer_behind_proxy(self): + """ + A POST HTTPS request is accepted when USE_X_FORWARDED_PORT=True. + """ + req = self._get_POST_request_with_token() + req._is_secure_override = True + req.META.update({ + 'HTTP_HOST': '10.0.0.2', + 'HTTP_REFERER': 'https://www.example.com/somepage', + 'SERVER_PORT': '8080', + 'HTTP_X_FORWARDED_HOST': 'www.example.com', + 'HTTP_X_FORWARDED_PORT': '443', + }) + req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {}) + self.assertIsNone(req2) + @override_settings(ALLOWED_HOSTS=['www.example.com'], CSRF_TRUSTED_ORIGINS=['dashboard.example.com']) def test_https_csrf_trusted_origin_allowed(self): """