flask jwt_extended explanation
Here is a full tutorial on how to implement JSON Web Tokens (JWT) in a Flask application using the Flask-JWT-Extended library:
- Install the necessary packages:
pip install flask-jwt-extended
2. Import the necessary modules into your Flask application:
from flask import Flask, request, jsonify
from flask_jwt_extended import JWTManager, jwt_required, create_access_token, get_jwt_identity
3. Initialize the JWT manager and add it to your Flask application:
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'your-secret-key' # change it to a secret key
jwt = JWTManager(app)
4. Create a route for handling user login and verify the user credentials:
@app.route('/login', methods=['POST'])
def login():
if not request.is_json:
return jsonify({"msg": "Missing JSON in request"}), 400
email = request.json.get('email', None)
password = request.json.get('password', None)
if email != 'test@example.com' or password != 'password':
return jsonify({"msg": "Bad email or password"}), 401
# Generate the JWT
access_token = create_access_token(identity=email)
return jsonify(access_token=access_token), 200
5. Decorate the routes that require authentication with the @jwt_required
decorator:
@app.route('/protected-route')
@jwt_required
def protected():
current_user = get_jwt_identity()
return jsonify(logged_in_as=current_user), 200
6. Send the JWT in the “Authorization” header for subsequent requests:
headers = {'Authorization': 'Bearer ' + access_token}
r = requests.get('http://localhost:5000/protected-route', headers=headers)
7. To handle token freshness, you could set up a route for refreshing tokens and create a new access token for the user with the same identity.
from datetime import timedelta
@app.route('/refresh', methods=['POST'])
@jwt_refresh_token_required
def refresh():
current_user = get_jwt_identity()
new_token = create_access_token(identity=current_user, expires_delta=timedelta(minutes=5))
return jsonify(access_token=new_token), 200
8. To handle token expiration, you could add the @jwt_expired_token_required
decorator to a route that can handle expired tokens
@app.route('/expired', methods=['POST'])
@jwt_expired_token_required
def expired():
return jsonify({"msg": "The token has expired"}), 401
This is a basic example of how to implement authentication in a Flask application using JWT and the Flask-JWT
Thank you for reading !!!
If you enjoy this article and would like to Buy Me a Coffee, please click here.
you can connect with me on Linkedin.