Jan 6, 2012

Django runserver and stunnel for testing HTTPS

To get a simple tunnel setup, we typically want to follow this route:

browser ---> https://localhost:8443 ---> http://localhost:8000 ---> runserver

Create ssl sertificate

That is, the routing of all requests on localhost port 8443 to localhost port 8000, which is where our Django runserver instance is serving up our web application and static content (if any). To setup this routing, I’ve created a simple stunnel configuration file, which also provides a few other configuration niceties, like outputting all messages to stdout rather than running silently in the background. The configuration file (fake_https) is represented below:
pid=

cert = path/to/your/stunnel.pem
sslVersion = SSLv3
foreground=yes
#debug = 7
#output = /path/to/stunnel.log

[https]
accept=8443
connect=8000
TIMEOUTclose=1
Be sure to note the use of the TIMEOUTclose option. Without this set to a low timeout value, you will notice a severe lag before your browser receives a close message. To run stunnel with this configuration, simply execute the following from the command line:
stunnel fake_https
Finally, you must tell Django’s runserver to modify all incoming HTTP requests to behave as if they were over HTTPS. This tells Django to set all request objects to return True for calls to request.is_secure(). This may be accomplished by simply setting the HTTPS environment variable to a non-zero value (i.e. True) prior to executing runserver. For example:
HTTPS=1 python manage.py runserver
You may now visit https://localhost:8443 in your web browser, and you should see activity in your stunnel terminal window and in your Django runserver terminal window, indicating a successful tunneling of all local SSL traffic to your basic Django runserver.

This simple method is a great way to test your web apps locally to ensure they behave correctly under secure and unsecure scenarios, including server-side handling of secure cookies.

http://stackoverflow.com/questions/8023126/how-can-i-test-https-connections-with-django-as-easily-as-i-can-non-https-connec