0
0
Flaskframework~30 mins

Session security in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Secure User Session in Flask
📖 Scenario: You are building a simple web app where users log in. You want to keep their session safe so no one else can use it.
🎯 Goal: Create a Flask app that sets up a secret key, stores a username in the session, and protects the session with secure settings.
📋 What You'll Learn
Use Flask's session to store user data
Set a secret key for the Flask app
Configure session cookie to be secure and HTTPOnly
Create a route to set the username in the session
Create a route to display the username from the session
💡 Why This Matters
🌍 Real World
Web apps use sessions to remember who you are after you log in. Keeping sessions secure stops others from pretending to be you.
💼 Career
Understanding session security is key for backend developers to protect user data and prevent attacks like session hijacking.
Progress0 / 4 steps
1
Set up Flask app and secret key
Import Flask and session from flask. Create a Flask app called app. Set app.secret_key to 'supersecretkey'.
Flask
Need a hint?

The secret key helps Flask keep session data safe. Use app.secret_key = 'supersecretkey'.

2
Configure session cookie security
Set app.config['SESSION_COOKIE_SECURE'] = True and app.config['SESSION_COOKIE_HTTPONLY'] = True to make the session cookie secure and inaccessible to JavaScript.
Flask
Need a hint?

These settings help protect the session cookie from being stolen or accessed by scripts.

3
Create a route to set username in session
Create a route /login that sets session['username'] = 'Alice' and returns the text 'Logged in as Alice'.
Flask
Need a hint?

Use @app.route('/login') and inside the function set session['username'] = 'Alice'.

4
Create a route to show username from session
Create a route /profile that returns f"Logged in user: {session.get('username', 'Guest')}" to display the username or 'Guest' if not logged in.
Flask
Need a hint?

Use @app.route('/profile') and return the username from session with a fallback to 'Guest'.