Welcome back! In the previous lessons, we learned how to create a basic login endpoint and integrate JSON Web Tokens (JWT) for authentication. By now, you should be familiar with setting up a Flask
application, validating user credentials using Marshmallow
, and generating JWTs upon successful login.
In this lesson, we will take a crucial step forward by learning how to secure an endpoint using JWT. Securing endpoints ensures that only authenticated users can access certain parts of your application, enhancing the overall security of your API.
To secure an endpoint using JWT, we will leverage the @jwt_required
decorator from the Flask-JWT-Extended
library. This decorator ensures that any request made to the decorated route must include a valid JWT.
Here's how you can create a protected route in your Flask application:
Python1from flask_jwt_extended import jwt_required 2 3# Define a route that requires a valid JWT to access 4@app.route('/protected', methods=['GET']) 5@jwt_required() 6def protected_route(): 7 return jsonify(message="This is a protected route, and you are authenticated!"), 200
By adding the @jwt_required
decorator, the endpoint is secured as it requires the presence of a valid JWT in the request headers. If the JWT is missing or invalid, the request will be denied.
With this setup, you can ensure that only authenticated users can access the /protected
endpoint.
If a client tries to access the protected endpoint without including the JWT token in the request, the server will respond with an error message indicating that the authorization header is missing. Here is an example of the response JSON for such a request:
JSON1{"msg": "Missing Authorization Header"}
To make a successful request to the protected endpoint, the client must first send a login request to obtain a JWT token. After obtaining the token, the client must include it in the Authorization
header of the HTTP request.
The header should be formatted as follows:
Plain text1Authorization: Bearer <your-token>
When a valid JWT token is provided, the server will allow access to the protected endpoint and return a success message, indicating that the client is authenticated.
JSON1{"message": "This is a protected route, and you are authenticated!"}
In this lesson, we covered the following key points:
Flask-JWT-Extended
's @jwt_required
decorator to secure an endpoint.You've now mastered how to secure an endpoint using JWT in Flask, ensuring that only authenticated users can access specific parts of your application. Up next, you will have the opportunity to practice what you've learned with hands-on exercises.
Keep up the great work, and let's continue fortifying our Flask application to make it even more robust and secure!