Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Right now I am using a flask 3rd party library Flask-Session and I am having no luck getting a session working.

When I connect to my site, I get the following error:

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

Below is my server code.

from flask import Flask, session
from flask.ext.session import Session

SESSION_TYPE = 'memcache'
    
app = Flask(__name__)
sess = Session()

nextId = 0

def verifySessionId():
    global nextId

    if not 'userId' in session:
        session['userId'] = nextId
        nextId += 1
        sessionId = session['userId']
        print ("set userid[" + str(session['userId']) + "]")
    else:
        print ("using already set userid[" + str(session['userId']) + "]")
    sessionId = session.get('userId', None)
    return sessionId

@app.route("/")
def hello():
    userId = verifySessionId()
    print("User id[" + str(userId) + "]")
    return str(userId)

if __name__ == "__main__":
    app.secret_key = 'super secret key'

    sess.init_app(app)

    app.debug = True
    app.run()

As you can see, I do set the app secret key. What am I doing wrong?

Are there other session options?

Other info: Running Python 2.7 on Linux Mint

Full paste:

Traceback (most recent call last):
  File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/sean/code/misc/session/sessiontest.py", line 27, in hello
    userId = verifySessionId()
  File "/home/sean/code/misc/session/sessiontest.py", line 16, in verifySessionId
    session['userId'] = nextId
  File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/werkzeug/local.py", line 341, in __setitem__
    self._get_current_object()[key] = value
  File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/sessions.py", line 126, in _fail
    raise RuntimeError('the session is unavailable because no secret '
RuntimeError: the session is unavailable because no secret key was set.  Set the secret_key on the application to something unique and secret.
like image 893
MintyAnt Avatar asked Sep 28 '14 01:09

MintyAnt


People also ask

How do you get a secret key in 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.

What is Flask session secret key?

app.run(debug=True) It's important to notice here is that we added the SECRET_KEY, when we add a secret key Flask automatically identifies it and makes the session object ready to be used. Secret Key should be generated as random as possible.

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.

What is Flask ext?

A Flask extension is a Python module, which adds specific type of support to the Flask application. Flask Extension Registry is a directory of extensions available. The required extension can be downloaded by pip utility.


3 Answers

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.

like image 91
Martijn Pieters Avatar answered Sep 21 '22 08:09

Martijn Pieters


Set the secret key outside of if __name__ == '__main__':

app.py:

from flask import Flask, session

app = Flask(__name__)
app.secret_key = "super secret key"

@app.route("/")
...

if __name__ == '__main__':
    app.debug = True
    app.run()

When you start your app by running flask run the if __name__ == '__main__': block gets skipped. If you don't want to skip it, run with python app.py.

like image 44
hayden Avatar answered Sep 22 '22 08:09

hayden


Try this:

app = Flask(__name__)
app.config['SESSION_TYPE'] = 'memcached'
app.config['SECRET_KEY'] = 'super secret key'
sess = Session()

And remove your app.secret_key assignment at the bottom.

like image 45
Miguel Avatar answered Sep 24 '22 08:09

Miguel