This middlware enforces HTTPS for logged in users and HTTP for others. This can be overridden with the require_https view decorator, which always enforces HTTPS.
It has been tested with Django 1.4.1 running on Python 2.6 and 2.7.
Put httpsmiddleware.py in to one of your apps and add the HTTPSMiddleware class to your MIDDLEWARE_CLASSES in settings.py:
MIDDLEWARE_CLASSES = (
...
'django.contrib.auth.middleware.AuthenticationMiddleware',
'myapp.httpsmiddlware.HTTPSMiddleware',
...
)
Note that HTTPSMiddleware must come after AuthenticationMiddleware. See the Django documentation on middlewares for further information about how the middlewares work.
When you have added the middleware to your project all authenticated users that open a page on your site through HTTP are redirected to HTTPS. To take full advantage of this it is highly recommended that you put the following line in your settings.py
SESSION_COOKIE_SECURE = True
This hides the session cookie when users connect through HTTP, mitigating man in the middle attacks. See then Django documentation on security for more information.
The HTTPSMiddleware adds a cookie when users log in that indicates that the logged in user is using the website. This cookie is not a secure cookie and can thus be seen when a user opens a page through HTTP. It is neccessary when SESSION_COOKIE_SECURE is set to True and not all requests are redirected to HTTPS.
This cookie is called authenticated_user
by default, but this can be
overridden in settings.py:
AUTH_COOKIE_NAME = 'new_name'