The foundation of contemporary web development is security. Understanding JWT Authentication in Flask is essential if you’re developing a backend application in order to safeguard user information and resources. Consider an API as a high-end hotel. Every time you want to go to the gym or enter your room, you don’t check your identity at the front desk. Instead, you get a key card after checking in once, which you then use to access different facilities.
JWT (JSON Web Token) functions similarly to that key card in the digital realm. Users can carry a secure token for future requests and confirm their identity only once. This guide breaks down complicated security concepts into easy-to-follow steps, making it your go-to flask jwt authentication tutorial.
Why Choose Flask for API Development?
Before we dive into the code, let’s understand why developers love Flask for building APIs. Its lightweight nature makes it a top choice for microservices and scalable applications.
Here is why you should use Flask for your next API project:
- Micro-framework design keeps the core simple and unbloated.
- The vast Python ecosystem offers massive library support.
- Flexible routing makes URL definition incredibly easy.
- A built-in development server speeds up the coding process.
- It scales efficiently for growing API demands.
- Extensions allow seamless integration of databases and authentication.
Understanding Token Based Authentication in Flask Python
As you begin to implement flask api security using jwt, you are no longer using sessions like a traditional server. In a session-based system, the server keeps track of all the logged-in users. This is perfectly fine for small applications but becomes cumbersome as you grow. JWT flips this on its head. When a user logs in, the server creates a token that is signed with a secret key. The server then hands this token off to the client.
For all subsequent requests, the client sends this token back. The server simply checks the signature. It doesn’t have to query a database to determine whether the user is “logged in.” This makes your application stateless and much faster.
Implementing JWT in Python Flask
In this example implementation, we will install required libraries and create few API endpoints for authentication and details. Here, we will create register, login, logout and user details endpoint.
Installing Flask and JWT Extensions
Before we dive into the code, you must set up your development environment. A clean environment ensures that your flask jwt authentication tutorial experience remains smooth and error-free. For securing flask api with jwt, we rely on Flask-JWT-Extended. This library simplifies the complex work of generating, verifying, and refreshing tokens. It works seamlessly with the core Flask framework.
Open your terminal or command prompt and run the following command to install the necessary packages:
pip install flask flask-jwt-extended
Creating Authentication APIs with Flask
We will now build a complete authentication flow. This includes registering a new user, logging in to receive a token, accessing a protected route, and logging out securely. For this flask jwt login example, we will use a temporary in-memory dictionary to store users and a “Blocklist” to handle logouts. In a production environment, you would replace the dictionary with a real database like PostgreSQL or MySQL.
Here is the complete code structure:
from flask import Flask, jsonify, request
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt, get_jwt_identity
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)
app.config["JWT_SECRET_KEY"] = "please-change-this-to-a-secure-key"
jwt = JWTManager(app)
users_db = {}
token_blocklist = set()
@jwt.token_in_blocklist_loader
def check_if_token_revoked(jwt_header, jwt_payload):
jti = jwt_payload["jti"]
return jti in token_blocklist
@app.route("/register", methods=["POST"])
def register():
username = request.json.get("username", None)
password = request.json.get("password", None)
if not username or not password:
return jsonify({"msg": "Missing username or password"}), 400
if username in users_db:
return jsonify({"msg": "User already exists"}), 400
users_db[username] = generate_password_hash(password)
return jsonify({"msg": "User created successfully"}), 201
@app.route("/login", methods=["POST"])
def login():
username = request.json.get("username", None)
password = request.json.get("password", None)
user_password_hash = users_db.get(username)
if not user_password_hash or not check_password_hash(user_password_hash, password):
return jsonify({"msg": "Bad username or password"}), 401
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token)
@app.route("/logout", methods=["DELETE"])
@jwt_required()
def logout():
jti = get_jwt()["jti"]
token_blocklist.add(jti)
return jsonify({"msg": "Token revoked"}), 200
if __name__ == "__main__":
app.run()
For the all endpoint, the client application send request with data and perform operation. The client sends a JSON object with a username and password. We check if the user exists. If they are new, we hash their password using generate_password_hash and save it to our users_db. This ensures that even if someone sees the database, they cannot read the passwords.
Once user is registered, they can send login request with username and password and script will return token. The jwt token will be used into further request to validation user. At last, Logout method will revoke generated token and return informative message.
Securing API endpoints
Our basic authentication is configured. Now, we move forward with creating secure APIs. Let’s assume we have endpoint which will return user details for logged in user and it has some sensitive data.
@app.route("/user", methods=["GET"])
@jwt_required()
def user_details():
current_user = get_jwt_identity()
return jsonify(
username=current_user,
email=f"{current_user}@example.com",
status="active"
), 200
This endpoint represents a protected resource. The @jwt_required() decorator ensures only users with a valid, non-blocked token can enter. We retrieve the current user’s identity with get_jwt_identity() to customize the response.
Conclusion
A secure authentication system has been put in place here. We created a working login system, went over the principles of JWT authentication in Flask, and discussed the advantages of a stateless API. Security doesn’t have to be difficult. Flask Python becomes a powerful tool for contemporary web services by utilizing token-based authentication. Always use HTTPS in production settings and keep your secret keys secure.
