Self-paced

Explore our extensive collection of courses designed to help you master various subjects and skills. Whether you're a beginner or an advanced learner, there's something here for everyone.

Bootcamp

Learn live

Join us for our free workshops, webinars, and other events to learn more about our programs and get started on your journey to becoming a developer.

Upcoming live events

Learning library

For all the self-taught geeks out there, here is our content library with most of the learning materials we have produced throughout the years.

It makes sense to start learning by reading and watching videos about fundamentals and how things work.

Search from all Lessons


LoginGet Started
← Back to Lessons
Edit on Github

Understanding JWT and how to implement a simple JWT with Flask

Implementing JWT in your project's front-end

JWT is just one of the ways you can implement security and specifically token based authentication in your API.

It is an open standard for creating tokens that are used in the authentication and authorization of web applications and APIs. JWT is a type of token that includes a structure that can be decrypted by the server and allows authenticating the identity of the user of an application.

Unlike other types of tokens, such as basic or Bearer tokens, JWT tokens are larger and contain all the necessary information without the need for an external database1.

JWT token structure

A JWT token consists of three parts separated by dots:

  • HEADER: Stores the token type and encryption algorithm.

  • PAYLOAD: Contains data that identifies the user, such as ID or username.

  • SIGNATURE: Digital signature generated with the two previous sections to verify if the content has been modified1.

Implementation in Flask:

To use JWT in a Flask API, you can follow these steps:

  • Include the JWT library in your Flask application configuration.

  • Create an endpoint to generate new tokens.

  • Use the @jwt_required() decorator in private routes.

Implementing JWT in your project API

We strongly recommend using JWT Extended library to implement JWT authentication in your Python Flask API. The process can be divided into the following steps:

1) Include the JWT library in your Flask App setup

1from flask_jwt_extended import JWTManager 2 3# You must already have this line in your project, you don't have to add it again 4app = Flask(__name__) 5 6# Setup the Flask-JWT-Extended extension 7app.config["JWT_SECRET_KEY"] = "super-secret" # Change this "super secret" to something else! 8jwt = JWTManager(app)

2) Create one endpoint for generating new tokens

The endpoint should be a POST because you are creating tokens (POST is for creation).

1POST /token 2Content-type: application/json 3Body: 4{ 5 "username": "alesanchezr", 6 "password": "12341234" 7}

This is how the endpoint could look like in Python:

1from flask_jwt_extended import create_access_token 2 3# Create a route to authenticate your users and return JWT Token 4# The create_access_token() function is used to actually generate the JWT 5@app.route("/token", methods=["POST"]) 6def create_token(): 7 username = request.json.get("username", None) 8 password = request.json.get("password", None) 9 10 # Query your database for username and password 11 user = User.query.filter_by(username=username, password=password).first() 12 13 if user is None: 14 # The user was not found on the database 15 return jsonify({"msg": "Bad username or password"}), 401 16 17 # Create a new token with the user id inside 18 access_token = create_access_token(identity=user.id) 19 return jsonify({ "token": access_token, "user_id": user.id })

3) Use the @jwt_required() decorator on private routes

Now... any endpoint that requires authorization (private endpoints) should use the @jwt_required() decorator.

You will be able to retrieve the authenticated user's information (if valid) using the get_jwt_identity function.

1from flask_jwt_extended import jwt_required, get_jwt_identity 2 3# Protect a route with jwt_required, which will kick out requests without a valid JWT 4@app.route("/protected", methods=["GET"]) 5@jwt_required() 6def protected(): 7 # Access the identity of the current user with get_jwt_identity 8 current_user_id = get_jwt_identity() 9 user = User.query.get(current_user_id) 10 11 return jsonify({"id": user.id, "username": user.username }), 200

Implementing JWT in your project's front-end

On the front-end side, we need two main steps: Creating a new token (a.k.a: login) and appending the token to the headers when fetching any other private endpoints.

Create new token:

Based on the endpoints we built earlier we have to POST /token with the username and password information in the request body.

1const login = async (username, password) => { 2 const resp = await fetch(`https://your_api.com/token`, { 3 method: "POST", 4 headers: { "Content-Type": "application/json" }, 5 body: JSON.stringify({ username, password }) 6 }) 7 8 if(!resp.ok) throw Error("There was a problem in the login request") 9 10 if(resp.status === 401){ 11 throw("Invalid credentials") 12 } 13 else if(resp.status === 400){ 14 throw ("Invalid email or password format") 15 } 16 const data = await resp.json() 17 // Save your token in the localStorage 18 // Also you should set your user into the store using the setItem function 19 localStorage.setItem("jwt-token", data.token); 20 21 return data 22}

Fetch any private information

Let's suppose I am using the front-end application and I just logged in, but now I want to fetch some private or protected endpoint:

1// Assuming "/protected" is a private endpoint 2const getMyTasks = async () => { 3 // Retrieve token from localStorage 4 const token = localStorage.getItem('jwt-token'); 5 6 const resp = await fetch(`https://your_api.com/protected`, { 7 method: 'GET', 8 headers: { 9 "Content-Type": "application/json", 10 'Authorization': 'Bearer ' + token // ⬅⬅⬅ authorization token 11 } 12 }); 13 14 if(!resp.ok) { 15 throw Error("There was a problem in the login request") 16 } else if(resp.status === 403) { 17 throw Error("Missing or invalid token"); 18 } else { 19 throw Error("Unknown error"); 20 } 21 22 const data = await resp.json(); 23 console.log("This is the data you requested", data); 24 return data 25}

That is it! As you can see, it's very simple to integrate JWT into your application using Flask/Python, just three steps on the backend and two steps on the front-ent. For any questions, you can contact me on Twitter @alesanchezr or use the #public-support channel on 4Geeks Academy's Slack community.