Last active
December 16, 2020 13:01
-
-
Save Alir3z4/84b48b149d4327ef1ab3 to your computer and use it in GitHub Desktop.
When running on AWS Elastic Beanstalk, we suffer an issue where HTTPS requests arriving at the load balancer are propagated to the individual hosts as HTTP requests. If the host issues a redirect it issues it using the same scheme as its incoming request (HTTP) when it should use HTTPS. This issue isn't unique to AWS EB, it's discussed in the co…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.http import HttpResponsePermanentRedirect | |
class SecureRequestPropagationMiddleware(object): | |
""" | |
When running on AWS Elastic Beanstalk, we suffer | |
an issue where HTTPS requests arriving at the load | |
balancer are propagated to the individual hosts as | |
HTTP requests. If the host issues a redirect it | |
issues it using the same scheme as its incoming | |
request (HTTP) when it should use HTTPS. | |
This issue isn't unique to AWS EB, it's discussed | |
in the context of WebFaction hosting in this | |
Django ticket: | |
https://code.djangoproject.com/ticket/12043 | |
This middleware addresses the problem, by | |
using the value of the X-Forwarded-Proto header | |
to manually set the wsgi.url_scheme header. | |
""" | |
def process_request(self, request): | |
""" | |
:type request: django.http.HttpRequest | |
:rtype: HttpResponsePermanentRedirect or None | |
""" | |
if 'HTTP_X_FORWARDED_PROTO' in request.META: | |
request.META['wsgi.url_scheme'] = request.META['HTTP_X_FORWARDED_PROTO'] | |
if request.is_secure(): | |
url = request.build_absolute_uri(request.get_full_path()) | |
if not url.startswith('https://'): | |
secure_url = url.replace('http://', 'https://') | |
return HttpResponsePermanentRedirect(secure_url) | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment