Home > other >  How to get read of django secret_key? is using get_random_secret_key() recommended?
How to get read of django secret_key? is using get_random_secret_key() recommended?

Time:06-09

I am wondering if I can generate secret key inside my django application and assign it to the SECRET_KEY variable instead of reading it from the env variables?

# settings.py

from django.core.management.utils import get_random_secret_key




SECRET_KEY = get_random_secret_key()

is it recommended or it is a bad practice?

CodePudding user response:

This would call get_random_secret_key() each time the settings are loaded, therefore setting a different SECRET_KEY every time, which is not good. From the docs:

The secret key is used for:

  • All sessions if you are using any other session backend than django.contrib.sessions.backends.cache, or are using the default get_session_auth_hash().
  • All messages if you are using CookieStorage or FallbackStorage.
  • All PasswordResetView tokens.
  • Any usage of cryptographic signing, unless a different key is provided.

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.

CodePudding user response:

Secret key provides cryptographic signing, If you rotate your secret key, all of the following will be invalidated (except passwords of users), so it is a bad practice to have them generated in each request.

  • All sessions if you are using any other session backend than django.contrib.sessions.backends.cache, or are using the default get_session_auth_hash().
  • All messages if you are using CookieStorage or FallbackStorage.
  • All PasswordResetView tokens. Any usage of cryptographic signing, unless a different key is provided.
  • Related