How to Protect Your Django Project's Secret Key

Mfon. - Jul 1 '22 - - Dev Community

I have been working on some Django tasks for a while. I mistakenly pushed my secret key to my public GitHub repository.😬 Yeah, rookie mistake! 🤷🏽‍♂️

I immediately received an email from GitGuardian informing me of the security risks involved.

GitGuardian security risk notification email

I took some steps to avoid this problem in subsequent tasks and projects. Before I get to that, I will briefly highlight some requirements.
P.S. I use VSCode on a windows device. 😁

Requirements

Use a .gitignore file.

  • A .gitignore file tells git what files and directories to ignore. Git will automatically ignore any file or directory put in this file to protect sensitive information.

  • Create .gitignore files at the root of your GitHub repository before you git-clone it to VSCode.

Create a virtual environment i.e. .env or .venv file.



#.env
py -3 -m venv .env
#.venv
py -3 -m venv .venv


Enter fullscreen mode Exit fullscreen mode
  • It is good practice to ignore your virtual environment by adding it into the .gitignore file, which you have included at the root of your repository.

Steps

On your command line, install python-dotenv with the following code:



pip install python-dotenv


Enter fullscreen mode Exit fullscreen mode

Go to your settings.py file and paste these two lines in your settings file:



from dotenv import load_dotenv
load_dotenv()


Enter fullscreen mode Exit fullscreen mode

Copy your secret key from your settings.py file and paste it into the .env or .venv file you created:



SECRET_KEY=ui#1j%%f5mxdojzakk72+dvftl%4&y#31_a##16s6s(6pfxy-b


Enter fullscreen mode Exit fullscreen mode
  • Remove the spaces before and after the equal sign

  • Remove the quotation marks

Next, in your settings.py file, you retrieve the secret key as follows:



SECRET_KEY = str(os.getenv('SECRET_KEY'))


Enter fullscreen mode Exit fullscreen mode

Tom Cat swallowing a key gif

You may need to add the import os function:
Django import os function

Run the server to see if it works before you stage and commit:



python manage.py runserver

Enter fullscreen mode Exit fullscreen mode




Note

  • I switched to Git Bash on VSCode. Some commands did not work as expected with other terminals.
    Git Bash terminal on VSCode

  • You may decide to try out any other terminal provided by VSCode:
    Terminals provided by VSCode

If you know other ways to solve this, kindly leave a comment. 👇🏽

Cheers! 🍻

References

Cover Image Source

. . . . . . . . . .