Django - How to keep secrets safe with python-dotenv

Often when working on a django project, we have some secret keys, OAuth keys and other critical information that needs to be kept safe and private. By no means should you expose such kind of keys because it makes your system vulnerable to security attacks.

Today, we are going to see how we can use python-dotenv to keep such kind of information hidden. As we can read from the docs, basically what python-dotenv does is read key-value pairs from a .env file and set them as environment variables to be retrieved later.

First and foremost let's install this module.

pip install python-dotenv

Then create a .env file in the root directory of our project. This is where we will put key value pairs of all the environment variables required by our application.

Okay, what should we put in the .env file?

  • The secret key that comes with every django project - This needs to be kept private because it's the crucial part of security in django.
  • Social auth configs for Github
  • Social auth configs for Google or any other OAuth keys.

.env

SECRET_KEY = 'YOUR SECRET KEY'

GITHUB_KEY = 'YOUR GITHUB KEY'
GITHUB_SECRET = 'YOUR GITHUB SECRET KEY'

GOOGLE_KEY = 'YOUR GOOGLE KEY'
GOOGLE_SECRET = 'YOUR GOOGLE SECRET KEY'
  • Pull these configs from .env and load them in the settings.

settings.py

from dotenv import load_dotenv
load_dotenv()  # loads the configs from .env

Now instead of exposing our secret keys and OAuth keys in the settings, let's retrieve them through their key names as follows.

settings.py

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = str(os.getenv('SECRET_KEY'))

# social auth configs for github
SOCIAL_AUTH_GITHUB_KEY = str(os.getenv('GITHUB_KEY'))
SOCIAL_AUTH_GITHUB_SECRET = str(os.getenv('GITHUB_SECRET'))

# social auth configs for google
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = str(os.getenv('GOOGLE_KEY'))
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = str(os.getenv('GOOGLE_SECRET'))

That's it, with these simple steps we are able to make our app more secure.

Thanks for your time. You can find the finished app in github. See you next time with another part of the series.

Any comments and suggestions are welcome.

29