Allowing users to log in to your app is one of the most common features you’ll add to your web application. This article will cover how to add authentication to your Flask app with the Flask-Login package.

Animated gif of the Flask app and login box

We’re going to build some sign-up and login pages that allow users to log in and access protected pages that users who aren’t logged in can’t see. We’ll grab information from the user model and display it on our protected pages when the user logs in to simulate what a profile would look like.

We will cover the following in this article:

  • Use the Flask-Login library for session management
  • Use the built-in Flask utility for hashing passwords
  • Add protected pages to our app for logged in users only
  • Use Flask-SQLAlchemy to create a user model
  • Create sign up and login forms for our users to create accounts and log in
  • Flash error messages back to users when something goes wrong
  • Use information from the user’s account to display on the profile page

The source code for this project is available on GitHub.

Here is a diagram to provide a sense of what your project’s file structure will look like once you have completed the tutorial:

.
└── flask_auth_app
    └── project
        ├── __init__.py       # setup our app
        ├── auth.py           # the auth routes for our app
        ├── db.sqlite         # our database
        ├── main.py           # the non-auth routes for our app
        ├── models.py         # our user model
        └── templates
            ├── base.html     # contains common layout and links
            ├── index.html    # show the home page
            ├── login.html    # show the login form
            ├── profile.html  # show the profile page
            └── signup.html   # show the signup form

As we progress through the tutorial, we will create these directories and files.

#flask #python #web-development #developer

How to Add Authentication to Your Flask App with Flask-Login Package
3.35 GEEK