Home > other >  Dynamic SECRET_KEY in Django disadvantages
Dynamic SECRET_KEY in Django disadvantages

Time:06-17

I just started learning Django and I'm wondering what the drawbacks of using a randomly generated SECRET-KEY would be. So far I've started with using this code...

from pathlib import Path import random, string

# Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# Randomized security key size = 100 SECRET_KEY = ''.join(random.choices(string.ascii_uppercase   string.ascii_lowercase
  string.punctuation   string.hexdigits   string.digits, k = size))

For now, this seems to work well for a simple blog that I made but I'm wondering what drawbacks this might have in other uses and if there are better ways of making the key secure.

Thanks in advance!

CodePudding user response:

You should indeed use a random-generated secret key, but it shouldn't be dynamically generated in the settings, as rotating the key invalidates active sessions, messages and tokens. From the docs:

The secret key is used for:

If you rotate your secret key, all of the above will be invalidated. Secret keys are not used for passwords of users and key rotation will not affect them.

Note: Don't use random.choices() to generate a secret key, as it is not cryptographically secure. You can use the secrets module for that:

import secrets
import string

choices = string.ascii_letters   string.digits   "<>()[]*?@!#~,.;"
key = "".join(secrets.choice(choices) for n in range(100))
  • Related