Authentication is a critical part of API security. It ensures that only authorized users can access certain resources or perform specific actions. One common method for API authentication is token-based authentication, where users are provided a token (usually a JWT - JSON Web Token) that proves their identity on each request.
In this article, we will explore how to implement token-based authentication in Flask APIs using the Flask-JWT-Extended extension for working with JWTs (JSON Web Tokens).
First, we need to install Flask and the Flask-JWT-Extended extension. You can do this by running the following commands:
pip install flask pip install flask-jwt-extended
Now, create a basic Flask application:
from flask import Flask, jsonify app = Flask(__name__) @app.route('/') def home(): return 'Welcome to the Flask API with Authentication!' if __name__ == '__main__': app.run(debug=True)
This sets up a basic Flask application that we will later modify to include authentication.
Flask-JWT-Extended provides a simple way to implement JWT-based authentication in your Flask app. The first thing we need to do is configure it in our Flask application.
from flask import Flask from flask_jwt_extended import JWTManager app = Flask(__name__) # Set up the secret key for encoding and decoding JWTs app.config['JWT_SECRET_KEY'] = 'your_jwt_secret_key_here' # Initialize JWTManager jwt = JWTManager(app) @app.route('/') def home(): return 'Welcome to the Flask API with JWT Authentication!' if __name__ == '__main__': app.run(debug=True)
In the above example, we set the JWT_SECRET_KEY
to a secret value, which is used to sign the JWT tokens. We also initialized the JWTManager
to manage token operations.
Now, let’s implement token-based authentication. We'll need two main operations:
To generate a token, we will create a login route. When a user logs in with valid credentials, we will return a JWT token:
from flask import Flask, request, jsonify from flask_jwt_extended import create_access_token app = Flask(__name__) app.config['JWT_SECRET_KEY'] = 'your_jwt_secret_key_here' jwt = JWTManager(app) users = {'user1': 'password123', 'user2': 'password456'} @app.route('/login', methods=['POST']) def login(): # Get the username and password from the request username = request.json.get('username', None) password = request.json.get('password', None) # Check if the username and password are correct if username in users and users[username] == password: # Create a JWT token access_token = create_access_token(identity=username) return jsonify(access_token=access_token), 200 else: return jsonify({"message": "Invalid credentials"}), 401 if __name__ == '__main__': app.run(debug=True)
In this example, the /login
endpoint checks if the provided username and password match any of the users. If they do, we generate an access token using create_access_token()
and send it back to the client.
Now, we’ll implement a protected route that requires the client to send the JWT token for authentication. We'll use the @jwt_required()
decorator to enforce this:
from flask import Flask, jsonify from flask_jwt_extended import JWTManager, jwt_required app = Flask(__name__) app.config['JWT_SECRET_KEY'] = 'your_jwt_secret_key_here' jwt = JWTManager(app) @app.route('/protected', methods=['GET']) @jwt_required() def protected(): return jsonify(message="This is a protected route.") if __name__ == '__main__': app.run(debug=True)
In this example, the /protected
route is protected by the @jwt_required()
decorator, meaning that a valid JWT must be provided for access. If no token is provided or the token is invalid, the user will receive an error.
Once you have the access token, the client needs to include the token in the headers of requests to protected routes. The token is typically sent in the Authorization
header with the Bearer
keyword:
Authorization: Bearer
In this article, we demonstrated how to implement token-based authentication in Flask APIs using the Flask-JWT-Extended extension. We created a login route to generate JWT tokens and a protected route to enforce token-based authentication.
JWT authentication is a powerful and flexible way to secure your API endpoints. With Flask-JWT-Extended, you can easily handle token-based authentication in your Flask applications, providing a secure mechanism for managing user sessions.