Skip to content
Advertisement

demystify Flask app.secret_key

If app.secret_key isn’t set, Flask will not allow you to set or access the session dictionary.

This is all that the flask user guide has to say on the subject.

I am very new to web development and I have no idea how/why any security stuff works. I would like to understand what Flask is doing under the hood.

  • Why does Flask force us to set this secret_key property?
  • How does Flask use the secret_key property?

Advertisement

Answer

Anything that requires encryption (for safe-keeping against tampering by attackers) requires the secret key to be set. For just Flask itself, that ‘anything’ is the Session object, but other extensions can make use of the same secret.

secret_key is merely the value set for the SECRET_KEY configuration key, or you can set it directly.

The Sessions section in the Quickstart has good, sane advice on what kind of server-side secret you should set.

Encryption relies on secrets; if you didn’t set a server-side secret for the encryption to use, everyone would be able to break your encryption; it’s like the password to your computer. The secret plus the data-to-sign are used to create a signature string, a hard-to-recreate value using a cryptographic hashing algorithm; only if you have the exact same secret and the original data can you recreate this value, letting Flask detect if anything has been altered without permission. Since the secret is never included with data Flask sends to the client, a client cannot tamper with session data and hope to produce a new, valid signature.

Flask uses the itsdangerous library to do all the hard work; sessions use the itsdangerous.URLSafeTimedSerializer class with a customized JSON serializer.

Advertisement