Last active
December 3, 2023 02:47
-
-
Save carltongibson/648099cd34b2c0a18e948c917a5c48fd to your computer and use it in GitHub Desktop.
Django Middleware to have `request.is_secure()` always return `True`. Maybe preferred to a WSGI middleware. Refs: https://noumenal.es/notes/til/django/csrf-trusted-origins/
This file contains hidden or 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
class HTTPSOnlyMiddleware: | |
""" | |
Override request.is_secure() to always return True. | |
Only use if you're **always** serving with HTTPS | |
**and** SECURE_PROXY_SSL_HEADER is not suitable for your setup. | |
""" | |
def __init__(self, get_response): | |
self.get_response = get_response | |
def __call__(self, request): | |
# Option 1: Main API — is_secure(): | |
def is_secure(): | |
return True | |
request.is_secure = is_secure | |
# Option 2: Lower level — _get_scheme(): | |
# ???: What **else** uses the `request.scheme` property? 🤔 | |
# def _get_scheme(): | |
# return 'https' | |
# | |
# request._get_scheme = _get_scheme | |
# Either way... | |
assert request.is_secure() | |
response = self.get_response(request) | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment