Using JWT Flask JWT Authentication- A Quick Guide
This tutorial helps you build a simple Flask API and demonstrates how to secure it using JWT. In the end, you can test your API authentication using a sample schema.

Table of Contents
- What is Authentication?
- Authentication Factors
- Single-factor Authentication
- Multi-factor Authentication
- Types of Authentication
- Authentication vs. Authorization
- Starter Application
- Authentication Middleware
- Auth Routes
- Protecting API Routes in Flask
- Conclusion
What is Authentication?
Authentication is an essential part of any web application. But unfortunately, it is not always easy to implement.
What is Authentication?
Authentication is a process of verifying that an entity is who they claim to be. For example, a user might authenticate by providing a username and password. If the username and password are valid, the system will check if the user can access the resource. After the system checks the user's details against its database and if the details are valid, the user is thus authenticated and can access available resources.
Authentication Factors
The following factors are used to authenticate a user.
Single-factor Authentication
This authentication is used when a user provides a username/email/phone number and a password. This is the most common and weakest authentication factor. The user simply inputs the email and password, and the system checks if the data is valid; if valid, the user gets authenticated and can access the resource. What happens if another person who is not a legitimate user tries to access the resource? The system denies access to the resource.
Multi-factor Authentication
This authentication uses more than one factor to authenticate a user. For example, the user tries to log in with, say, email and password; if the data is correct, a code is sent to the user's phone number, and the user is asked to input the code. If the user enters the code, the user gets logged in; otherwise, the user is not authenticated. Some applications even go a step further by not using two factors but using three factors.
Types of Authentication
There are three types of authentication, as follows:
- Knowledge Authentication: The user is asked something that only they can provide or know -- e.g., password. This is the most common type and also the easiest.
- Property Authentication: The user is asked for something they own or possess. For example, they can use a hardware authentication device like YubiKey or an authenticator app on their phone. The idea is that users will be asked to set an authentication factor that verifies the identity more securely. This isn’t always used alone; it’s used alongside another authentication type, say, .
- Biological Authentication: The user is asked to verify their identity using something biologically unique to them -- e.g., a fingerprint or iris scan.
In most applications, knowledge and property authentication are used as an extra layer of authentication.
Authentication vs. Authorization
The following are the differences between authentication and authorization:
-
Authentication verifies identity (usually through credential validation)) while authorization grants or denies permissions to a user.
-
Authentication is used to verify that users are who they say they are. Authorization is used to verify that a user has permission to do something.
Starter Application
In this tutorial, you'll work on authentication in flask middleware for an existing API built with Flask and PyMongo. The API is a book library API using which users can create books and upload cover images for the books and relevant data. PyMongo is used to connect to the mongo database. You'll use the PyJWT library to generate and verify JWT tokens for auth in flask.
You can learn more about JSON Web Tokens (JWT) here.
To get started, clone the repository and set up the application by running the following commands:
The application is now set up and ready to run. You can run the app using the command in the project directory. You can test that all the endpoints are working by testing the app in an API testing tool, like Postman.
Authentication Middleware
As you've noticed, anybody can access the API; you need to restrict access to the API. Create new book data if they have the correct data, then add, delete, and update book data, but you don't want that. To do this, you need to implement an authentication middleware.
When we talk about authentication with flask, middlewares are created in Flask by creating a decorator; a function can have multiple middlewares, and the order matters a lot.
To create your auth middleware, you need to install PyJWT -- the library you'll use to generate tokens. You’ll also use Pillow to alter image data before saving them to disk. Run the following command to install the packages:
You need to add a secret key to your application; this is what you should pass to JWT.
Add the following to your file below the app declaration.
Let's create a file called in the root of your application and place the following inside this file:
The function above is simply a decorator function. Inside this function, you check if there is an field in the headers part of the request; if this is missing, you return an authorization error.
Next, you check if it exists but is not valid; if it is not valid, you also return an authorization error.
If everything goes fine, then the view function is called. As you can see, you return , where is the next decorator or function that's being called after this decorator -- in your case, the view function, which means that the first argument of any view function that uses this decorator must be .
Auth Routes
You currently have a route to creating a new user, but you don't have one to log in. From what you have above, you're checking if the token passed as the header is valid, but now the question is -- how do you get to know the token. Basically, the login route fetches the token and sends it to the client.
Add the following function below the function:
Protecting API Routes in Flask
So far, you've been able to create your auth middleware, but you need to use this middleware to protect routes. All you need to do is to pass this middleware immediately after the middleware, then make the first argument of the view function, as follows:
Add this middleware () to every function you only want authenticated users to access. In the end, your whole file should look as follows.
Before running the application, let's look at the function inside the file. This is the function responsible for saving uploaded pictures.
You should also add the following functions as helper methods of the model class.
Your file should look as follows:
Here's an example of the user request:
Here, the name should have two words, and the password should have at least an uppercase later, a lower case letter, a digit, and a special character.
And an example of the book request:
While passing a book request, pass it via the tab in Postman.
Conclusion
This article has explained flask JWT authentication .
In some cases, handling flask authentication yourself may not be good enough or efficient -- to overcome this, you can simply use third-party authentication providers like LoginRadius. You can check out this tutorial to learn how to add LoginRadius to your Flask application.
You can find the complete code for this article on Github. You can reach out to me on Twitter if you've any questions.

Featured Posts
How to Implement JWT Authentication for CRUD APIs in Deno
Multi-Factor Authentication (MFA) with Redis Cache and OTP
Introduction to SolidJS
Build a Modern Login/Signup Form with Tailwind CSS and React
Implement HTTP Streaming with Node.js and Fetch API
NestJS: How to Implement Session-Based User Authentication
NestJS User Authentication with LoginRadius API
How to Authenticate Svelte Apps
Flutter Authentication: Implementing User Signup and Login
How to Secure Your LoopBack REST API with JWT Authentication
Node.js User Authentication Guide
Your Ultimate Guide to Next.js Authentication
Local Storage vs. Session Storage vs. Cookies
How to Secure a PHP API Using JWT
Using JWT Flask JWT Authentication- A Quick Guide
Build Your First Smart Contract with Ethereum & Solidity
What are JWT, JWS, JWE, JWK, and JWA?
How to Build an OpenCV Web App with Streamlit
32 React Best Practices That Every Programmer Should Follow
How to Build a Progressive Web App (PWA) with React
Bootstrap 4 vs. Bootstrap 5: What is the Difference?
JWT Authentication — Best Practices and When to Use
What Are Refresh Tokens? When & How to Use Them
How to Upgrade Your Vim Skills
How to Implement Role-Based Authentication with React Apps
How to Authenticate Users: JWT vs. Session
How to Use Azure Key Vault With an Azure Web App in C#
How to Implement Registration and Authentication in Django?
11 Tips for Managing Remote Software Engineering Teams
Implementing User Authentication in a Python Application
Add Authentication to Play Framework With OIDC and LoginRadius