The background

Method #1

An easy and safe way to handle sessions is to do the following:

  • Use a session cookie that contains a session ID (a random number).
  • Sign that session cookie using a secret key (to prevent tempering — this is what itsdangerous does).
  • Store actual session data in a database on the server side (index by ID, or use a NoSQL key / value store).
  • When a user accesses your page, you read the data from the database.
  • When a user logs out, you delete the data from the database.

Note that there are a few drawbacks.

  • You need to maintain that database backend (more maintenance)
  • You need to hit the database for every request (less performance)

Method #2

Another option is to store all the data in the cookie, and sign (and optionally encrypt) said cookie. This method, however, has numerous shortcomings too:

  • This is easier on the backend (less maintenance, better performance).
  • You need to be careful to not include data your users should not see in sessions (unless you're encrypting).
  • The volume of data you can save in a cookie is limited.
  • You can't invalidate an individual session (!).

The code

Flask actually implements signed session cookies already, so it implements method #2.

To get from #2 to #1, all you have to do is:

  • Generate random Session IDs (you could use os.urandom + base64).
  • Save session data in a database backend, indexed by Session ID (serialize it using e.g. JSON, Picke if you need Python objects, but avoid if you can).
  • Delete sessions from your database backend when a user logs out.

Make sure you're protected against session fixation attacks. To do so, make sure you generate a new session ID when a user logs in, and do not reuse their existing session ID.

Also, make sure you implement expiration on your sessions (just a matter of adding a "last-seen" timestamp).

You could most likely get some inspiration from Django's implementation.

Answer from Thomas Orozco on Stack Overflow
🌐
Miguel Grinberg
blog.miguelgrinberg.com › post › how-secure-is-the-flask-user-session
How Secure Is The Flask User Session? - miguelgrinberg.com
April 4, 2016 - I have actually landed here because i was wondering how Flask prevents CSRF - mainly with oAuth. When implementing oAuth the tutorial recommends adding a state variable/token in the session object.
🌐
Rustcodeweb
rustcodeweb.com › 2025 › 05 › flask-session-security.html
Flask: Session Security | RUSTCODE
May 18, 2025 - This tutorial explores Flask session security, covering secure session configurations, protection against common attacks, and integration with authentication, with practical applications in secure web development.
Discussions

security - How to properly and securely handle cookies and sessions in Python's Flask? - Stack Overflow
I wanted to review the security of my solution and I stared to look into how I should be setting up cookies upon login, what to store in server side stored session and how to destroy that information on logout since as of now my users were staying logged in for ages, which was not my intention. The problem I have is no definite answer on how to handle the whole user login/session/logout issue properly in Flask ... More on stackoverflow.com
🌐 stackoverflow.com
Is the default flask session still not secure?
I’m not aware of a specific session vulnerability in Flask that has not been patched. But if you are referring to the idea that client side sessions in general are considered insecure, you would be right. Server side sessions are a better way to go in my opinion. However, if the data in the session isn’t sensitive, I don’t think it matters much, but honestly server side sessions are pretty easy to implement, so why not? Here is a link to a YouTube video regarding server side sessions in Flask: https://youtu.be/lvKjQhQ8Fwk More on reddit.com
🌐 r/flask
4
1
November 6, 2020
How to implement Authentication when using Flask as backend and Vue.JS as frontend

There's nothing really wrong with using session cookies with an API. A cookie is just a header, every http client can use them, and they're especially convenient for web apps.

A long lived jwt ( no refresh token ) is also fine if you validate against your database on every request and have a system to blacklist tokens.
The refresh token flow is pretty much designed for high traffic APIs where you can't afford to verify access on every request.
Until you have enough traffic where that becomes a problem, you don't need to worry about it.

More on reddit.com
🌐 r/flask
19
40
November 24, 2019
Flask-Login vs. Flask-User vs Flask-Security

I think Flask-Security is deprecated right now. I never used Flask-User on a project. Flask-Login was always my choice for handling sessions/users. You can make your own session handler. I recommend using JWT for authentication & authorization.

More on reddit.com
🌐 r/flask
26
18
May 28, 2019
🌐
Medium
medium.com › featurepreneur › secure-flask-sessions-with-encryption-a-step-by-step-guide-833061d5599f
Secure Flask Sessions with Encryption: A Step-by-Step Guide | by Mohammed Farmaan | featurepreneur | Medium
January 3, 2024 - This key is crucial for both encrypting and decrypting session data. Ensure that you keep it secure and never expose it publicly. Add the following function to your Flask application to encrypt session data:
Top answer
1 of 2
30

The background

Method #1

An easy and safe way to handle sessions is to do the following:

  • Use a session cookie that contains a session ID (a random number).
  • Sign that session cookie using a secret key (to prevent tempering — this is what itsdangerous does).
  • Store actual session data in a database on the server side (index by ID, or use a NoSQL key / value store).
  • When a user accesses your page, you read the data from the database.
  • When a user logs out, you delete the data from the database.

Note that there are a few drawbacks.

  • You need to maintain that database backend (more maintenance)
  • You need to hit the database for every request (less performance)

Method #2

Another option is to store all the data in the cookie, and sign (and optionally encrypt) said cookie. This method, however, has numerous shortcomings too:

  • This is easier on the backend (less maintenance, better performance).
  • You need to be careful to not include data your users should not see in sessions (unless you're encrypting).
  • The volume of data you can save in a cookie is limited.
  • You can't invalidate an individual session (!).

The code

Flask actually implements signed session cookies already, so it implements method #2.

To get from #2 to #1, all you have to do is:

  • Generate random Session IDs (you could use os.urandom + base64).
  • Save session data in a database backend, indexed by Session ID (serialize it using e.g. JSON, Picke if you need Python objects, but avoid if you can).
  • Delete sessions from your database backend when a user logs out.

Make sure you're protected against session fixation attacks. To do so, make sure you generate a new session ID when a user logs in, and do not reuse their existing session ID.

Also, make sure you implement expiration on your sessions (just a matter of adding a "last-seen" timestamp).

You could most likely get some inspiration from Django's implementation.

2 of 2
3

I would recommend you go with the Flask KVSession plugin with the simplekv module to persist the session information.

Conceptually, Flask KVSession provides an implementation for Method #1 described above using the Flask session interface. That way you don't have to alter your code to get it running, and you can use the extension methods to do additional things such as session expiration. It also takes care of the session signing, and does some basic checks to prevent tampering. You will still want to do this over HTTPS to absolutely prevent session stealing however.

Simplekv is the actual module that handles the writing and reading to various data storage formats. This can be as simple as a flat file, as fast as Redis, or as persistent as a database (NoSQL or otherwise). The reason this is a separate module is so Flask KVSession can just be a plain adapter to Flask without having to know about the storage mechanism.

You can find code samples at http://flask-kvsession.readthedocs.org/en/latest/. If you need more examples, I can provide one.

Alternatively, if you need a more enterprise and heavyweight server sided implementation for Flask, you can also look at this recipe using Beaker which works as WSGI middleware (meaning other frameworks also use it). http://flask.pocoo.org/snippets/61/. The Beaker API is at http://beaker.readthedocs.org/en/latest/.

One advantage Beaker provides over Flask KVSession is that Beaker will lazy load sessions, so if you don't read the session information, it won't make a connection to the database on every call. However, Beaker depends on SQLAlchemy which is going to be a larger module than simplekv module.

Unless that specific performance case is important, I would still go with Flask KVSession because of its slightly simpler API and smaller code base.

🌐
Tech with Tim
techwithtim.net › tutorials › flask › sessions
Flask Tutorial - Sessions
from flask import Flask, redirect, url_for, render_template, request, session · While we are at it we will import another module that we’ll use later. ... Since the session information will be encrypted on the server we need to provide flask with a secret key that it can use to encrypt the data.
🌐
Flask
flask.blog › flask-session-tutorial
Flask Session Tutorial: How to Manage User Sessions in Flask
Before you start working with sessions, you must set a SECRET_KEY for your Flask app. This key is used to securely sign session cookies.
🌐
Readthedocs
flask-session.readthedocs.io › en › latest › security.html
Security - Flask-Session 0.8.0 documentation
You can use a security plugin such as Flask-Talisman to set these and more. Take care to secure your storage and storage client connection. For example, setup SSL/TLS and storage authentication. Session fixation is an attack that permits an attacker to hijack a valid user session.
Find elsewhere
🌐
BinaryScripts
binaryscripts.com › flask › 2025 › 01 › 20 › session-management-and-security-in-flask-for-production.html
Session Management and Security in Flask for Production | BinaryScripts
April 3, 2025 - In this blog, we will cover secure session management techniques, common vulnerabilities, and best practices to protect user sessions in Flask applications.
🌐
Medium
medium.com › top-python-libraries › flask-sessions-and-cookies-managing-user-data-across-requests-f313a64ed85f
Flask Sessions and Cookies: Managing User Data Across Requests | by Jayendra | Top Python Libraries | Medium
November 19, 2024 - from flask import Flask, session, redirect, url_for, request, render_template_string app = Flask(__name__) app.secret_key = 'your_secret_key' # Set a secret key to secure the session
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-add-authentication-to-your-app-with-flask-login
Add Authentication to Flask Apps with Flask-Login | DigitalOcean
October 22, 2025 - Flask-Login is the most popular authentication library for Flask applications, handling user sessions, login state, and route protection with minimal configuration. This tutorial shows you how to implement secure user authentication in Flask using Flask-Login, Flask-SQLAlchemy, and Werkzeug’s password hashing utilities.
🌐
DEV Community
dev.to › fullstackstorm › working-with-sessions-in-flask-a-comprehensive-guide-525k
Working with Sessions in Flask: A Comprehensive Guide - DEV Community
October 9, 2023 - Before diving into sessions, make sure you have Flask installed. If not, you can install it using pip: ... Flask relies on a secret key to secure sessions.
🌐
Gist.ly
gist.ly › youtube-summarizer › flask-tutorial-managing-sessions-and-cookies-for-secure-user-experience
Flask Tutorial: Managing Sessions and Cookies for Secure User Experience
May 1, 2024 - Learn how to use sessions and cookies in Flask to securely keep track of user information across multiple requests. Also, master message flashing to display status messages with ease.
🌐
Descope
descope.com › blog › post › auth-flask-app
How to Add Authentication in Flask
June 26, 2025 - In this tutorial, we’ll build authentication in Flask using Descope for handling user sessions. The app will let users sign up, sign in, log out, and view a profile page. We’ll manage authentication in Flask by combining Python, HTML templates, ...
🌐
TestDriven.io
testdriven.io › blog › flask-spa-auth
Session-based Auth with Flask for Single Page Apps | TestDriven.io
September 23, 2022 - This article looks at how to add session-based authentication to a Single-Page Application (SPA) powered by Flask and Svelte.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-use-flask-session-in-python-flask
How to use Flask-Session in Python Flask - GeeksforGeeks
July 23, 2025 - This article demonstrates how to implement server-side sessions in Flask using the Flask-Session extension. We’ll create a simple app that remembers a user’s name between requests, enabling login and logout functionality.
🌐
Readthedocs
flask-login.readthedocs.io › en › latest
Flask-Login 0.7.0 documentation
Alternatively, if USE_SESSION_FOR_NEXT is True, the page is stored in the session under the key next. If you would like to customize the process further, decorate a function with LoginManager.unauthorized_handler: @login_manager.unauthorized_handler def unauthorized(): # do stuff return a_response · For example: You are using Flask Login with Flask Restful.
🌐
Python Geeks
pythongeeks.org › python geeks › learn flask › python flask session
Python Flask Session - Python Geeks
May 17, 2023 - You can do this by setting the SECRET_KEY configuration option, which is used to encrypt the session data. The SECRET_KEY should be a random and secure value, as it is used to protect the integrity of the session data.
🌐
TestDriven.io
testdriven.io › blog › flask-sessions
Sessions in Flask | TestDriven.io
June 4, 2023 - This cookie is sent with each request ... cookies that are cryptographically-signed (not encrypted!), sessions should NOT be used for storing any sensitive information....
🌐
Miguel Grinberg
blog.miguelgrinberg.com › post › cookie-security-for-flask-applications
Cookie Security for Flask Applications - miguelgrinberg.com
With Flask, you can control the secure flag on the session cookie with the SESSION_COOKIE_SECURE configuration setting. By default, it is set to False, which makes the session cookie available to both HTTP and HTTPS connections.
🌐
AskPython
askpython.com › home › flask sessions – setting user sessions in flask
Flask Sessions - Setting User Sessions in Flask - AskPython
December 2, 2020 - Hence to Tackle that, We keep all ... Okay, let us now dive into the coding part. In Flask, a dictionary object called session object is used to track the session data....