Skip to content

Instantly share code, notes, and snippets.

@carltongibson
Last active December 3, 2023 02:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carltongibson/648099cd34b2c0a18e948c917a5c48fd to your computer and use it in GitHub Desktop.
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/
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