Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Intro to Secure Web Applications with Flask

thenerdnook.substack.com/p/intro-to-secure-web-applications

Josh Wenner

Welcome to my introduction on Authentication with Flask. Building upon our previous articles
that introduced you to Flask Web Development, we now jump into the world of
Authentication. We will soon be exploring Django, the next step up!

This article is all about adding authentication to a Flask application. I'll walk you through the
fundamental concepts, analyze provided code examples, and demonstrate how to implement
user authentication in Flask.

Throughout this guide, you'll gain insights into the basics of secure authentication with Flask.
Today I will use a dummy database to demonstrate the creation of such authentication
features you can implement in your own Flask Applications.

Each week, I dive deep into Python, breaking it down into bite-sized pieces. But here's the
kicker – while everyone else gets just a taste, my premium readers get the whole feast! Don't
miss out on the full experience – join us today!

20% Lifetime Discount

1/10
In last week’s Comprehensive Guide I included SQL Alchemy and JavaScript. I taught you
how we can create a Model to store user information before sending it off to an interactive
database. We also added the ability to register new users!

Authentication plays a pivotal role in safeguarding sensitive data and managing user access.
By the end of this article, you'll have a firm grasp on setting up authentication in Flask,
enhancing both security and user experience in your applications.

Before delving into authentication, if you haven't already, check out our Flask CRUD Project
on Project X. This article here pairs perfectly with the project, offering you the opportunity to
enhance your skills and integrate authentication into your CRUD app today!

This article will not include SQL Alchemy, Models or the ability to register. You can read my
comprehensive authentication guide here and join as a premium member today to get a
lifetime 20% discount along with access to more code examples with all my source code!

This is the Weekly Free Article. Premium Readers get Access to all my Source Code!

👉 If you get value from this article, please leave it a ❤️. This helps more people discover
this newsletter on Substack, which helps me out and shows me you enjoy content like this!

Why is Authentication Important?

When it comes to web applications, user authentication is like the front door to a secure
house. It’s the crucial first step in making sure that only the right people get in and that their
private information stays safe.

Protecting User Data: Authentication makes sure that a user’s personal data and
information are only accessible to them or people they’ve given permission to.

Ensuring Privacy: By preventing unauthorized access, authentication safeguards the


privacy of each user.

Managing Users Efficiently: With authentication, you can keep track of who is logged in,
what they’re doing, and personalize their experience.

Now, let’s dive into the code example and see how to set up authentication in Flask. We'll
break it down step-by-step to understand how it works and how you can implement it in your
own applications.

Setting Up Flask and SQLAlchemy

Flask Application Setup

2/10
First, we need to set up a basic Flask application. Here's the code snippet to get you started:

In the code above, I'm setting up my Flask project. I start by importing all the necessary
modules, then create a Flask app, and finally configure a basic dictionary that will be used as
my testing database for this introduction to authentication build.

You can add as many users to this dummy database, but this here is just the one I will use
for testing. Upon successful testing I can implement a real world database by using SQL
Alchemy and creating a Model to store our user information.

3/10
The above code is from my comprehensive guide where I introduced the ability to add SQL
Alchemy and Models with our Authentication app. I start by importing all the necessary
modules, then create a Flask app, and finally configure my SQL Alchemy database.

SQLAlchemy acts as a bridge between Python and the database, allowing us to work with
the database using Python classes and objects. We configure SQL Alchemy by specifying
the database URI and disabling modification tracking, as demonstrated in the code snippet.

Are you ready to learn more? Let me guide you through creating an interactive database with
SQL Alchemy and adding the ability to register new users for your application!

20% Off Premium

👉 If you’re getting value from this article, please leave it a ❤️. This helps more people
discover this newsletter on Substack, which helps me out and shows me you enjoy content
like this!

Setting Up Our Routes

Home Route

This function represents the initial page users encounter when they visit our web application.
In Flask, this page is always represented by the URL "/", which signifies the main page or
index of our app.

If the user is logged in, they are redirected to their personalized dashboard page. This page,
typically named "dashboard.html" in our app, provides a unique experience tailored to each
user.

However, if the user is not logged in or doesn't have an account yet, they are directed to our
login page, represented by "index.html". This is where users can log in to access the
features of our web application.

4/10
Login Route

This function handles user login, gathering real-time data from our HTML file. Specifically,
our HTML file contains a form with various input fields. We collect the information entered
into these fields and pass it to our User class for processing.

These are different code examples than my premium readers get access to. The one you are
seeing below pairs with our example here in our free article.

Once we've sent the user's information to our class to confirm their identity, we can direct
them to their personalized landing page if they're trying to log in. However, if they haven't
created an account yet, they remain on the index page and are prompted to sign up.

This function handles a POST request containing a username and password. It checks if the
username exists and if the password is correct. If the credentials are valid, the user is logged
in, and their session is updated. Otherwise, an error message is returned.

👉 If you’re getting value from this article, please leave it a ❤️. This helps more people
discover this newsletter on Substack, which helps me out and shows me you enjoy content
like this!

Register Route

This step is crucial because initially, you won't have any users in your database. I've added a
register button to the homepage. When clicked, it takes the information the user has entered
and creates a new entry in our database.

5/10
The ability to Register new users to your database is included in my premium content. Ready
to learn more? Let me guide you through creating an interactive database with SQL Alchemy
and adding the ability to register new users for your application!

Join as a premium reader

Logout Route

The final step in this introduction to authentication with Flask is to allow users to log out of
their accounts.

Think of the session as a list that keeps track of user information. When a user clicks the
logout button, we're simply removing their username from this list, effectively logging them
out.

After logging out, the user is redirected back to the homepage, which is the first page they
saw when they initially visited our application. This ensures a smooth and clear transition out
of their account.

Template Integration in Flask

Template integration in Flask lets you create dynamic and interactive web applications by
separating HTML structure from Python code. Using templates, you can generate HTML
dynamically and reuse layouts across multiple pages.

6/10
With the Jinja2 templating engine, you can pass data from your Flask routes to your HTML
templates, displaying user-specific information and rendering forms easily. This approach
helps you build organized, responsive, and user-friendly web applications.

Base HTML

This is the base.html file, which serves as the foundation for all other HTML files in our
Flask application. Using a base template is a common practice in Flask because it helps
streamline development and ensures that we only need to include the basic boilerplate code
once.

In this base file, we use Jinja syntax, which allows us to dynamically insert content. For
instance, we use Jinja in the href attribute of the link tag to include CSS files.

We also define a block called body where the content from other pages will be inserted. This
makes it easy to maintain a consistent look and feel across all pages of the web application.

Index HTML with Javascript

This is the index.html file, which extends our base.html template. By extending the base
template, we ensure that this page inherits the common structure and styles defined in
base.html, making our development process more efficient and consistent.

7/10
In this file, we create a form for user authentication, allowing users to either log in or register.
The form includes fields for the username and password, and two buttons: one for logging in
and another for registering.

We're using JavaScript here to dynamically set the form's action based on which button the
user clicks. The setFormAction function changes the form's action URL and method before
submitting the form.

This approach is useful because it allows us to use the same form for both login and
registration, reducing redundancy and simplifying the code. If we did not use Javascript here
then I would need to create two individual forms for both the login and registration process.

Dashboard HTML

This is the dashboard.html file, which extends our base.html template. By extending the
base template, this page inherits the common structure and styles defined in base.html,
ensuring a consistent look and feel across the application.

8/10
In this file, we create a personalized dashboard for the logged-in user. The {{ username }}
placeholder dynamically displays the user's name, making the page more welcoming and
specific to the user.

The dashboard includes a heading with the user's name, a paragraph indicating that this is
their dashboard, and a logout button. The logout button uses a link to the logout route,
allowing users to log out and end their session.

👉 If you’re getting value from this article, please leave it a ❤️. This helps more people
discover this newsletter on Substack, which helps me out and shows me you enjoy content
like this!

Conclusion

Incorporating authentication into Flask requires several steps: creating a user model, setting
up routes for login, registration, and the dashboard, and handling user sessions.

This guide lays a strong groundwork for your Flask projects, ensuring they're secure and
easy to use. Always prioritize securing your secret keys and employ hashing techniques to
safeguard user passwords and data.

I’ve been having a lot of fun breaking down Flask for you guys as I am working on a CRM
built around Flask. Using the skills I introduced to you guys in our last project and
incorporating the things talks about here today!

Have an amazing and blessed week Python crew! ~ Josh

9/10
FAQs

Why is authentication important in web applications?

Authentication ensures that users are who they say they are, protecting sensitive data from
unauthorized access.

How does Flask manage user sessions?

Flask uses the session object to store information about the user's session, such as their
username, across different requests.

What is SQLAlchemy?

SQLAlchemy is an ORM that allows you to interact with the database using Python objects
and classes, making database operations more intuitive.

The Nerd Nook is a reader-supported publication. To receive new posts and support my
work, consider becoming a free or paid subscriber.

Hey guys, my story is rather bizarre on how I got here…

I started a new blog surrounding my journey through life.

Let me know your thoughts, a different writing style from me!

Feel free to check out Life’s a B*tch here.

Thank you for taking the time to read this week’s article!

👉 If you enjoyed this article, please leave it a ❤️. This helps more people discover this
button is located right below here! ⤵️
newsletter on Substack, which helps me out and shows me you enjoy content like this! The

10/10

You might also like