Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not generate the secret key every time Flask starts?

When using sessions, Flask requires a secret key. In every example I've seen, the secret key is somehow generated and then stored either in source code or in configuration file.

What is the reason to store it permanently? Why not simply generate it when the application starts?

app.secret_key = os.urandom(50) 
like image 376
Arseni Mourzenko Avatar asked Dec 04 '14 06:12

Arseni Mourzenko


People also ask

Is secret key necessary in Flask?

Each Flask web application contains a secret key which used to sign session cookies for protection against cookie data tampering. It's very important that an attacker doesn't know the value of this secret key.

How do you get the secret key in the Flask?

Generate the Secret Key Using Different Ways in Flask and Python. To access a session ID, you need to use an encryption key assigned to the SECRET_KEY variable, so at the time, we set the value of the SECRET_KEY variable as a string is extremely dangerous. This key needs to be randomly generated.

How long should secret keys be?

It is actually an asymmetric key-pair with a length typically between 256 and 4,096 bits depending on the digital signature algorithm used. Such a key usually has a lifetime of several years, and the private key will often be protected using an HSM.


1 Answers

The secret key is used to sign the session cookie. If you had to restart your application, and regenerated the key, all the existing sessions would be invalidated. That's probably not what you want (or at least, not the right way to go about invalidating sessions). A similar case could be made for anything else that relies on the secret key, such as tokens generated by itsdangerous to provide reset password urls (for example).

The application might need to be restarted because of a crash, or because the server rebooted, or because you are pushing a bug fix or new feature, or because the server you're using spawns new processes, etc. So you can't rely on the server being up forever.

The standard practice is to have some throwaway key commited to the repo (so that there's something there for dev machines) and then to set the key in the local config when deploying. This way, the key isn't leaked and doesn't need to be regenerated.

There's also the case of running secondary systems that depend on the app context, such as Celery for running background tasks, or multiple load balanced instances of the application. If each running instance of the application has different settings, they may not work together correctly in some cases.

like image 130
davidism Avatar answered Sep 22 '22 09:09

davidism