Learn Flask · 10/15

Authentication & Authorization: Securing Your App

11 min read

Authentication & Authorization: Securing Your App 🛡️

Welcome to the crucial chapter on making your Flask application secure! Authentication and Authorization are the digital bouncers of your app, ensuring only the right people get in and they only do what they're allowed to. It might sound intimidating, but we'll break it down into easy-to-digest pieces.

Ready to become a security champion? Let's dive in!


1. Password Hashing and Security with Werkzeug

The What and Why of Password Hashing

Definition: Password hashing is the process of transforming a password into an unreadable string of characters. This is a one-way process, meaning the original password cannot be easily retrieved from the hashed version.

The Problem: Imagine you're building a clubhouse and everyone writes their secret password on a sticky note and sticks it on the door. If a mischievous individual comes by, they can read all the passwords and get in. Storing passwords as plain text in your database is the digital equivalent of this sticky note disaster. If your database is ever compromised, all your users' passwords are exposed. 😱

The Solution: Hashing to the rescue! Instead of storing the password itself, we store its "hash." When a user tries to log in, we take the password they entered, hash it, and then compare that hash to the one we have stored. If they match, we let them in. This way, even if someone gets a peek at your database, they won't see the actual passwords.

What About... Just Hashing? (The Salt Story)

A funny thing about basic hashing is that if two people have the same simple password (e.g., "password123"), their hashed passwords will be identical. Attackers can use pre-computed tables of common passwords and their hashes, called "rainbow tables," to quickly find a match.

This is where salting comes in. A salt is a random string of characters that we add to each password before hashing it. This ensures that even if two users have the same password, their stored hashes will be completely different. It's like adding a unique secret ingredient to each person's password recipe before baking it into a hash.

Enter Werkzeug: Your Security Sidekick

Werkzeug is a powerful WSGI utility library that Flask is built upon, and it comes with some excellent security helpers. We'll be using its generate_password_hash and check_password_hash functions.

Installation

If you have Flask installed, you already have Werkzeug! If not, a simple pip install will do the trick:

bash
pip install Werkzeug
Hands-On: Hashing and Checking Passwords

Let's see this in action. Fire up a Python interpreter and try this out:

python
from werkzeug.security import generate_password_hash, check_password_hash

# Imagine this is the password a user submitted through a form
password = "supersecretpassword"

# Now, let's hash it!
hashed_password = generate_password_hash(password)

print(f"The hashed password is: {hashed_password}")

# Now, let's pretend a user is logging in and we need to check their password
is_correct = check_password_hash(hashed_password, "supersecretpassword")
print(f"Is the password correct? {is_correct}")

is_incorrect = check_password_hash(hashed_password, "wrongpassword")
print(f"Is the password correct? {is_incorrect}")

Under the Hood: When you use generate_password_hash, Werkzeug automatically handles the salting for you. The resulting string contains the hashing method, the salt, and the hash itself, all neatly packaged. The check_password_hash function knows how to unpack this and do a secure comparison.

Interesting Fact: The default hashing algorithm in recent versions of Werkzeug is scrypt. It's designed to be computationally intensive, which means it's slow for attackers trying to guess passwords by hashing billions of possibilities (a brute-force attack).


2. Implementing User Registration and Login Flows

Now that we know how to handle passwords securely, let's build the doors to our digital clubhouse: the registration and login pages.

The Big Picture: How it Works

  1. Registration: A new user fills out a form with their details (like a username, email, and password). We take this information, hash the password, and save it all in our database.
  2. Login: A returning user enters their credentials. We look up the user in our database, hash the password they just entered, and compare it with the stored hash. If they match, we grant them access.

It's like a secret handshake. At registration, they teach us the handshake. At login, they perform it, and we check if it's the one we learned.

Building the Forms 📝

For handling forms in Flask, we'll keep it simple for now and use basic HTML forms.

Here’s a sneak peek at a registration form in an HTML file (e.g., templates/register.html):

html
<form method="post">
    <label for="username">Username</label>
    <input type="text" id="username" name="username" required>

    <label for="password">Password</label>
    <input type="password" id="password" name="password" required>

    <button type="submit">Register</button>
</form>

The login.html would look very similar. Notice the method="post"? This tells the browser to send the form data to our server in the body of the request, which is more secure than sending it in the URL.

The Flask Side of Things

Now, let's create the Flask routes to handle these forms.

python
from flask import Flask, render_template, request, redirect, url_for, flash
from werkzeug.security import generate_password_hash, check_password_hash

# A simple in-memory "database" for demonstration
users = {}

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        if username in users:
            flash('Username already exists!', 'error')
            return redirect(url_for('register'))

        hashed_password = generate_password_hash(password)
        users[username] = hashed_password

        flash('Registration successful! Please log in.', 'success')
        return redirect(url_for('login'))

    return render_template('register.html')


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        if username not in users or not check_password_hash(users[username], password):
            flash('Please check your login details and try again.', 'error')
            return redirect(url_for('login'))

        # Here, you would typically log the user in (more on this in the next section!)
        flash('Login successful!', 'success')
        return redirect(url_for('dashboard')) # A protected page

    return render_template('login.html')

Key Concepts in the Code:

  • request.method: This helps us differentiate between a user just visiting the page (GET) and a user submitting the form (POST).
  • request.form: A dictionary-like object that holds the data from our submitted form.
  • flash(): A handy Flask function for showing one-time messages to the user. For example, "Registration successful!". You'll need to set a SECRET_KEY for your app for flash messages to work.
  • redirect(url_for(...)): After a successful form submission, it's a good practice to redirect the user to another page. This prevents issues like the user accidentally resubmitting the form by refreshing the page. url_for() is a nifty function that generates the URL for a given view function, so you don't have to hardcode URLs.

A Funny Exaggeration: Not using redirect after a POST request is like having a conversation where after you answer a question, the person immediately asks you the exact same question again. It's awkward and can lead to duplicate orders in our imaginary e-commerce site!


3. Managing User Sessions with Flask-Login

The Problem: We can now register and "log in" users, but our app has the memory of a goldfish. Once a user logs in and moves to another page, the app forgets who they are. We need a way to remember that a user is logged in across different requests.

The Solution: Sessions! A session is like a temporary storage space on the server for a particular user. When a user logs in, we can put a little note in their session that says, "Hey, this person is authenticated!" For every subsequent request from that user, we can check for this note.

Doing this manually can be a bit of a chore. Thankfully, we have a fantastic extension called Flask-Login to handle the heavy lifting.

What is Flask-Login?

Flask-Login is an extension that provides user session management for Flask. It handles the common tasks of logging in, logging out, and remembering users' sessions. It's like hiring a friendly and very organized doorman for your app.

Installation

Let's get it installed:

bash
pip install flask-login

Getting Started with Flask-Login

To use Flask-Login, we need to do a few things:

  1. Initialize it: We need to create a LoginManager instance and initialize it with our Flask app.
  2. Create a User model: Flask-Login needs a representation of our users. This is typically a class that maps to our users table in the database.
  3. Implement a user_loader function: This is a function that tells Flask-Login how to find a specific user from our database given their ID.
The User Model

Let's create a simple User class. For Flask-Login to work with our User objects, they need to have a few specific properties and methods. The easiest way to get all of these is to inherit from UserMixin.

python
from flask_login import UserMixin

class User(UserMixin):
    def __init__(self, id):
        self.id = id

# We'll also update our in-memory store to use these User objects
users = {} # { 'username': (hashed_password, user_object) }

The UserMixin provides default implementations for methods like is_authenticated, is_active, is_anonymous, and get_id().

Initializing and Configuring Flask-Login

Now, let's set up the LoginManager:

python
from flask import Flask
from flask_login import LoginManager

app = Flask(__name__)
# DON'T FORGET to set a secret key for session management!
app.config['SECRET_KEY'] = 'a-super-secret-key-that-is-not-this'

login_manager = LoginManager()
login_manager.init_app(app)

@login_manager.user_loader
def load_user(user_id):
    # In a real app, you'd look up the user in your database
    # For our example, we'll retrieve it from our dictionary
    for username, (password_hash, user_obj) in users.items():
        if user_obj.id == user_id:
            return user_obj
    return None

The user_loader is crucial. Flask-Login will use the user's ID stored in the session to call this function and get the current user object for each request.

Tying it all Together: login_user and logout_user

Flask-Login provides two very helpful functions: login_user and logout_user.

Let's update our login and add a logout route:

python
from flask_login import login_user, logout_user, current_user

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        if username not in users or not check_password_hash(users[username][0], password):
            flash('Please check your login details and try again.')
            return redirect(url_for('login'))

        # Here's the magic!
        user = users[username][1]
        login_user(user)

        return redirect(url_for('dashboard'))

    return render_template('login.html')

@app.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('index')) # Redirect to the homepage

Now, when a user successfully logs in, login_user(user) will store their ID in the session. For any subsequent page they visit, Flask-Login will use our user_loader to retrieve the User object, which we can then access via the current_user proxy!

Real-life Scenario: Think of login_user as giving a visitor a wristband at a music festival. As they go to different stages (pages in our app), the security staff (user_loader) can quickly check their wristband to see if they're allowed in. logout_user is like cutting off the wristband when they leave.


4. Protecting Routes: Using the @login_required Decorator

We've come a long way! Users can register, log in, and our app remembers them. But there's one last piece to the puzzle.

The Problem: Right now, anyone can visit any page in our application, whether they are logged in or not. For example, a user who isn't logged in could just type /dashboard into their browser's address bar and see the dashboard. We need to put a guard at the door of our protected pages.

The Solution: The @login_required decorator from Flask-Login.

What is a Decorator?

In Python, a decorator is a function that takes another function and extends its behavior without explicitly modifying it. Think of it as putting a fancy hat on a function to give it new abilities. In Flask, we've already been using the @app.route() decorator to turn our functions into view handlers.

The @login_required Guard

Flask-Login provides a super convenient decorator called @login_required. When you place this decorator on a view function, it will ensure that the current user is logged in and authenticated before they can access that view.

If a user who is not logged in tries to access a protected page, Flask-Login will automatically redirect them to the login page.

How to Use It

It's as simple as adding one line of code!

python
from flask_login import login_required, current_user

@app.route('/dashboard')
@login_required
def dashboard():
    return f'<h1>Welcome to your dashboard, {current_user.id}!</h1>'

@app.route('/profile')
@login_required
def profile():
    return 'This is your super secret profile page.'

Now, if a user who isn't logged in tries to go to /dashboard or /profile, they will be sent to the login page.

Customizing the Redirect

By default, @login_required redirects to a view named login. If your login view function is named something else, you need to tell the LoginManager.

python
login_manager.login_view = 'name_of_your_login_view'

For our example, since our function is named login, the default works perfectly.

Accessing the Logged-In User

Inside a view protected by @login_required, you can confidently use the current_user object. Flask-Login ensures it will be the actual user object from your database.

python
@app.route('/settings')
@login_required
def settings():
    # You can access attributes of your User model here
    # For example, if your User model had a 'username' attribute:
    # username = current_user.username
    return f'Settings for {current_user.id}'

An Amusing Analogy: Using @login_required is like having a "You Must Be This Tall to Ride" sign for your web pages. Except, instead of height, it's "You Must Be Logged In." And instead of a thrilling roller coaster, it's... well, your awesome dashboard!

And that's a wrap on the fundamentals of Authentication and Authorization in Flask! You've learned how to securely store passwords, create registration and login flows, manage user sessions with Flask-Login, and protect your routes. You are now well-equipped to build secure and user-friendly web applications. 🥳


Further Reading & References

Challenge

Challenge: Implement Full User Authentication

You are provided with a skeleton Flask application that includes an in-memory dictionary to act as a user database. Your task is to implement a complete authentication and authorization system using the Werkzeug and Flask-Login libraries.

Requirements:

  1. Import Dependencies: At the top of the file, import all the necessary components: LoginManager, UserMixin, login_user, logout_user, login_required, current_user from flask_login, and generate_password_hash, check_password_hash from werkzeug.security.
  2. Configure Flask-Login: Initialize the LoginManager, configure it for the Flask app, and set its login_view to direct unauthenticated users to the login route.
  3. Enhance the User Model: Modify the provided User class to inherit from UserMixin to integrate it with Flask-Login.
  4. Implement the User Loader: Create the user_loader callback function, decorated appropriately. This function must retrieve a user from the users dictionary using their ID.
  5. Build the Registration Logic: In the register route, get the username and password from the form data. Use generate_password_hash to securely hash the password before creating and storing a new User object in the users dictionary.
  6. Implement the Login Logic: In the login route, find the user by their username. If the user exists, validate their submitted password against the stored hash using check_password_hash. If valid, use login_user to establish a session for them.
  7. Protect the Dashboard: Secure the /dashboard route by applying the @login_required decorator, ensuring only logged-in users can access it.
  8. Create the Logout Functionality: In the logout route, call the logout_user function to terminate the user's session.

Expected result

The final code should correctly implement a full authentication system. The solution must contain the following key elements:

  • Imports: The code begins with from werkzeug.security import generate_password_hash, check_password_hash and from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user.
  • Flask-Login Setup: The LoginManager is initialized (login_manager = LoginManager()), attached to the app (login_manager.init_app(app)), and configured with the login view (login_manager.login_view = 'login').
  • User Model: The User class definition is updated to class User(UserMixin):.
  • User Loader: The load_user function is decorated with @login_manager.user_loader and correctly implemented to return users.get(int(user_id)).
  • Registration Route: The register view uses generate_password_hash(request.form['password']) to create a secure password hash and correctly adds a new User instance to the users dictionary.
  • Login Route: The login view iterates through the users dictionary to find a user by username. It then uses check_password_hash(user.password_hash, request.form['password']) for validation. Upon success, it calls login_user(user) and redirects to the dashboard.
  • Protected Route: The dashboard view function is preceded by the @login_required decorator on its own line.
  • Logout Route: The logout view contains the call logout_user() to clear the user's session.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.