The SECRET_KEY to the Django Girls Tutorial

While going through the Django Girls Tutorial the other day in preperation for being a coach, I got to the point of posting my first update to Github, and that's when it happened...a dreaded nastygram from GitGuardian regarding my nascent git repo.

Git Guardian nastygram
Git Guardian nastygram

OOPS! what have I done? I broke one of the cardinal rules of coding. NEVER NEVER NEVER push secrets to Source Code Management. How can we avoid this? Well, there are a couple of small modifications you can do to your code to prevent this:

  • You could follow this tutorial, but that is fairly involved for an introductory lesson.
  • You could put it into an Environment Variable

I am going to talk about this last point here. So as you go through the tutorial, you will get to the point of putting a SECRET_KEY in your settings file. This can be dangerous, as it can open your app up to an attack vector. Instead you can put this into your environment:

In Linux:

export SECRET_KEY='put a totally secure secret key here'
or Windows:
setx SECRET_KEY "put a totally secure secret key here"



Once you have done this, you can run:

In Linux:

echo $SECRET_KEY
or Windows:
echo %SECRET_KEY%

to make sure it worked. Once you have done this, we need to tell Django and Python to get the secret key from our environment. You can do this by modifying two files:
  • settings.py
  • wsgi.py


In settings.py, replace the following line
SECRET_KEY = ''
with this:
SECRET_KEY = os.getenv("SECRET_KEY")
In wsgi.py, simply add this line:
SECRET_KEY = os.getenv('DJANGO_GIRLS_SECRET_TOKEN')
That's it! You now have a more secure way to set the secret key. Don't forget to run
export SECRET_KEY='put a totally secure secret key here'
in PythonAnywhere!

Comments

Popular Posts