Why Not Generate the Secret Key Every Time Flask Starts

Why not generate the secret key every time Flask starts?

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.

Where do I get SECRET_KEY for Flask?

The secret key is needed to keep the client-side sessions secure. You can generate some random key as below:

>>> import os
>>> os.urandom(24)
'\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'

Just take that key and copy/paste it into your config file

SECRET_KEY = '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'

See Sessions documentation

Cannot create secret key in flask; returns “name 'session' is not defined”

You are not importing session;

from flask import Flask, session

Check more details about flask session here;

https://pythonbasics.org/flask-sessions/#:~:text=Unlike%20cookies%2C%20Session%20(session),temporary%20directory%20on%20the%20server.

secret key not set in flask session, using the Flask-Session extension

In your case the exception is raised by the NullSessionInterface session implementation, which is the default session type when you use Flask-Session. That's because you don't ever actually give the SESSION_TYPE configuration to Flask; it is not enough to set it as a global in your module. The Flask-Session quickstart example code does set a global, but then uses the current module as a configuration object by calling app.config.from_object(__name__).

This default doesn't make much sense with Flask 0.10 or newer; NullSession may have made sense with Flask 0.8 or 0.9, but in current version the flask.session.NullSession class is used as an error signal. In your case it gives you the wrong error message now.

Set the SESSION_TYPE configuration option to something else. Pick one of redis, memcached, filesystem or mongodb, and make sure to set it in app.config (directly or via the various Config.from_* methods).

For a quick test, setting it to filesystem is easiest; there is enough default configuration there to have that work without additional dependencies:

if __name__ == "__main__":
# Quick test configuration. Please use proper Flask configuration options
# in production settings, and use a separate file or environment variables
# to manage the secret key!
app.secret_key = 'super secret key'
app.config['SESSION_TYPE'] = 'filesystem'

sess.init_app(app)

app.debug = True
app.run()

If you see this error and you are not using Flask-Session, then something has gone wrong with setting the secret. If you are setting app.config['SECRET_KEY'] or app.secret_key in a if __name__ == "__main__": guard like above and you get this error, then you are probably running your Flask app via a WSGI server that imports your Flask project as a module, and the __name__ == "__main__" block is never run.

It is always better to manage configuration for Flask apps in a separate file, anyway.

the session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret. Flask/Heroku

I have the same issue when I use flask-login to generate a session ID, it works fine when I directly run it but will output error when I use HTTP server. The original code is like:

if __name__ == "__main__":
app.secret_key = os.urandom(24)
app.run()

Then I moved app.secret_key = os.urandom(24) out of __name__ and put it under app = Flask(__name__) like this:

app = Flask(__name__)
app.secret_key = os.urandom(24)

login_manager = flask_login.LoginManager()
login_manager.init_app(app)

And it works fine now.

How can I resolve these flask 500 server errors?

Not completely sure if this causes your errors but you should definitely change this:

You have to set app.secret_key to a static value rather than os.urandom(24), e.g.:

app.secret_key = "/\xfa-\x84\xfeW\xc3\xda\x11%/\x0c\xa0\xbaY\xa3\x89\x93$\xf5\x92\x9eW}"

With your current code, each worker thread of your application will have a different secret key, which can result in errors or session inconsistency depending on how you use the session object in your application.

demystify Flask app.secret_key

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.

RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret

It has nothing to do with cache. In order to use sessions you have to set a secret key: http://flask.pocoo.org/docs/1.0/quickstart/#sessions

Add the following (obviously don't use my example and change the secret key) after initialising your app:

app = Flask(__name__)

# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'


Related Topics



Leave a reply



Submit