This tutorial will provide a step-by-step guide on how to implement JWT (JSON Web Token) authentication in a Flask API. JSON Web Tokens (JWT) are an open, industry standard RFC 7519 method for representing claims securely between two parties. They allow you to authenticate users and protect your endpoints.
By the end of this tutorial, you will learn:
- How JWT works
- How to implement JWT authentication in Flask
- How to use JWT to secure your Flask API endpoints
Prerequisites:
- Basic understanding of Python
- Familiarity with Flask
- Basic understanding of APIs
JWT consists of three parts: Header, Payload, and Signature. The header typically consists of two parts: the type of the token, which is JWT, and the signing algorithm being used. The payload contains the claims or the pieces of information being passed about the user and any additional data. The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn't changed along the way.
Before we can start working with JWT in Flask, we need to install Flask-JWT-Extended, a Flask extension that provides JWT functionality.
pip install flask-jwt-extended
Let's start by creating a basic Flask Application.
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/')
def home():
return jsonify(message = 'Welcome to the Flask JWT Tutorial!')
if __name__ == '__main__':
app.run(debug=True)
We can define protected routes that require a valid JWT to access.
from flask_jwt_extended import JWTManager, jwt_required, create_access_token
app.config['JWT_SECRET_KEY'] = 'your-secret-key' # Change this!
jwt = JWTManager(app)
@app.route('/login', methods=['POST'])
def login():
username = request.form.get("username")
password = request.form.get("password")
if username == 'test' and password == 'password': # Change this!
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token)
else:
return jsonify(message="Invalid credentials"), 401
@app.route('/protected', methods=['GET'])
@jwt_required
def protected():
return jsonify(message='You have accessed a protected endpoint!'), 200
In the above example, /login
route authenticates the user and returns a JWT. The /protected
route is a protected endpoint that requires a valid JWT to access.
In this tutorial, we've learned how JWT works and how to use it in Flask to secure our API endpoints. We've also learned how to create JWTs and how to protect routes with JWT.
Next Steps:
- Learn about refresh tokens and how to use them in Flask-JWT-Extended
- Learn about role-based access control in JWT
Additional Resources:
- Flask-JWT-Extended Documentation
- JWT Introduction
Exercise 1: Create a registration endpoint that returns a JWT upon successful registration.
Exercise 2: Add role-based access control to your API. Only allow users with an admin role to access certain endpoints.
Tips for Further Practice:
- Try to implement JWT authentication in a larger Flask project
- Learn about JWT blacklisting and how to implement it in Flask