Django runserver and stunnel for testing HTTPS
Recently I was testing a Django web app that required SSL enabled in order to retrieve a secure cookie for use server-side. After some quick google and stackoverflow searches, it appeared that simple tunneling with stunnel was the way to go. Unfortunately most of the documentation for doing this is typical unhelpful RTFM-isms.
To get a simple tunnel setup, we typically want to follow this route:
browser ---> https://localhost:8443 ---> http://localhost:8000 ---> runserver
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 is represented below:
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:
sudo 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.
20 Notes/ Hide
-
determinesek6 liked this
-
security980dek liked this
-
giveaway69bop liked this
-
xu4949 liked this
-
mgile posted this
