Flask session key

As we saw in the article Session in Flask, we have a Flask Session Key to be able to create a cookie with the session information. And Flask uses the cookie mechanism to have information between each of the requests made by the user.

To create the Flask session key we use the following code:

app.secret_key = 'this-is-a-very-secret-key'

From that moment on Flask will use this key to encrypt the cookie information.

At this point the question is, should I encrypt all cookies with the same key? The answer is obviously no, that is, we should try to encrypt users with different keys.

In order to solve this we can go to the operating system library os and use a random generation method such as .urandom()

The first thing of all will be to import the system library:

import os

Now we will simply have to assign the value of the .urandom() method to the Flask session key. Keep in mind that the .urandom() method has as its value the number of bytes that we want to return. The content returned is a string.

app.secret_key = os.urandom(24)

In this way we will ensure that the encryption key used as the session key in Flask is completely random and thus achieve good encryption of the cookie.