Flask Secret Key

Salman Mehmood Jul 04, 2022
Flask Secret Key

This article is about the secret key in Flask.

  1. What is a secret key?
  2. Why do we need to use it within the session?
  3. How can we generate the secret key using different ways?
  4. How is it useful when working with the debug toolbar 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.

Why is that so important? Well, if the client tries to manipulate data within the session ID, we want it to be rejected by the server.

If the client can somehow guess the secret key, then they can generate their session data which the server will not reject, and you can probably guess it; that is why it is not good practice.

So what is the session ID for? Well, it is stored inside a cookie and used to link the user to specify data on the server-side, like information about the user in the database.

The question then becomes: how do we generate a truly random key?

Let’s go and turn to the Flask docs; if we scroll down to the section where it says how to generate good keys, according to the documentation, your operating system has ways to generate pretty random stuff based on a random cryptographic generator that can be used to get such a key.

While following the docs, we open up a Python shell and import the os module, then use the urandom() function and pass 24 inside this function so that you can generate a random string with a link the size of the attribute which we passed.

import os

os.urandom(24)

When we hit Enter or print it, we get this key.

b'o\xe8\xc3VS\xf3\xf8\x0c\x80Y\xad\xb6\x86\xb3\x7f\xee\x98l\x80\xe47\xfb]}'

This secret key does not work for your Flask app, so you must generate it from your system. After generating a key, grab that string, go back to the Flask application and assign it to the SECRET_KEY variable.

There are several ways to get the secret key, and we will look at one more way to generate a hexadecimal key. To generate this key, we need to import the uuid module, and from the uuid4() function, we will use the hex property.

import uuid

uuid.uuid4().hex

Output:

'd5fb8c4fa8bd46638dadc4e751e0d68d'

In Flask, there is another way to define a secret key by self; to define the secret key, we can use the following code.

app.config["SECRET_KEY"] = "Define_The_Key"

When working with the debug toolbar in the Flask app, it is necessary to define a secret key because DebugToolbarExtension does not work without defining our secret key in the Flask app. We can use any method to define a secret key.

The complete source code of the example.

from flask import Flask, render_template
from flask_debugtoolbar import DebugToolbarExtension

# import os
# os.urandom(24)

# import uuid
# uuid.uuid4().hex

app = Flask(__name__)

app.debug = True
# app.config['SECRET_KEY']='Define_The_Key'

HEX_SEC_KEY = "d5fb8c4fa8bd46638dadc4e751e0d68d"

app.config["SECRET_KEY"] = HEX_SEC_KEY
TBAR = DebugToolbarExtension(app)


@app.route("/", methods=["GET"])
def DEB_EX():
    return render_template("index.html")


if __name__ == "__main__":
    app.run()

When we run the server, we can see the toolbar is working properly, and no error has occurred in the console.

Generate Secret Key using Flask

We used this code in our template.

<html>
    <head>
        <body>
            <h2>Hi User, the secret key is necessary to run the debug toolbar</h2>
        </body>
    </head>
</html>
Salman Mehmood avatar Salman Mehmood avatar

Hello! I am Salman Bin Mehmood(Baum), a software developer and I help organizations, address complex problems. My expertise lies within back-end, data science and machine learning. I am a lifelong learner, currently working on metaverse, and enrolled in a course building an AI application with python. I love solving problems and developing bug-free software for people. I write content related to python and hot Technologies.

LinkedIn