DjangoのSECRET_KEY

A secret key for a particular Django installation. This is used to provide cryptographic signing, and should be set to a unique, unpredictable value.

django-admin startproject automatically adds a randomly-generated SECRET_KEY to each new project.

SECRET_KEYは暗号署名のために一意で予測不能な値にする必要がある。
django-admin startprojectで自動的にsetting.pySECRET_KEYにランダムな値が追加される。

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.

  • Sessions
    • django.contrib.sessions.backends.cache以外のセッションバックエンドを使用する場合
    • get_session_auth_hash()を使用する場合
  • messages
    • CookieStorageかFallbackStorageを使用する場合
  • PasswordResetView Tokens
  • Cryptographic signing
    • 異なる鍵が提供されない場合

setting.pyからSECRET_KEYの値を外だしする

GitリポジトリにSECRET_KEYをPushしないように、setting.pyに埋め込まれたSECRET_KEYを環境変数にして管理する。

1
2
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['SECRET_KEY']

.envファイルで環境変数を管理している場合は以下のように設定。

1
SECRET_KEY=e=+g9j8XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX@k8wj0&