What is SECRET_KEY in Django?

Posted by Chris Bartos on July 17, 2017

Do you ever want to know how the SECRET_KEY works? It’s sitting in your settings.py file but do you ever wonder why you need it? If you look at the documentation, you’ll discover some very interesting things about the SECRET_KEY setting.

In the Cryptographic signing section of the Django docs, it says:

You may also find signing useful for the following:

  • Generating “recover my account” URLs for sending to users who have lost their password.
  • Ensuring data stored in hidden form fields has not been tampered with.
  • Generating one-time secret URLs for allowing temporary access to a protected resource, for example a downloadable file that a user has paid for.

And I’m going to add one more thing to this list: Signing cookies so that you know that your users’ cookies are not being tampered by a hacker.

How can you use the SECRET_KEY to determine if data has been tampered?

The first thing you need to do is sign your data.

from django.core.signing import Signer

signer = Signer()
value = signer.sign("My secret data")
value

Now, your signed data is saved in the value variable. How do you make sure that your data hasn’t been tampered with?

from django.core import signing

value += 'd'
try:
    original = signer.unsign(value)
except signing.BadSignature:
    print ("Tampering detected!")

If the value is different, the unsign function will throw a BadSignature exception. The Signer class uses the setting.SECRET_KEY to create the hash of the signed data.

Next time you have data that you need to keep from being tampered remember the Signer class.

Similar Posts

What is a Mixin
How to Use a Virtual Environment to run you Django app


What do you do after the Official Django Tutorial?

Here's what you'll learn:

  1. Start writing tests
  2. Increase the size / complexity of the Polls application.
  3. Learn how to code in Django by reading the Django source code.
  4. Finding code snippets to use in your website by reading the code of other websites.
  5. Using Javascript in a web app.
  6. Deploying on Heroku and AWS.
We won't send you spam. Unsubscribe at any time. Powered by ConvertKit


Get some value from this post? Please like and share this post because more people also deserve some value. :-)