Fullstack Flask API: Handling JSON Web Tokens (JWT) and Authorization
In modern web development, securing APIs is a top priority. JSON Web Tokens (JWT) have become a popular standard for implementing secure and stateless authentication. In a fullstack Flask application, handling JWTs effectively ensures that only authenticated users can access protected routes and resources. This blog will walk you through the fundamentals of JWT, how to implement it in a Flask API, and how to use it for user authorization.
What is JWT?
JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way to securely transmit information between parties as a JSON object. A typical JWT consists of three parts:
Header – contains the token type and signing algorithm.
Payload – holds the data (claims) such as user ID or roles.
Signature – verifies the token hasn’t been altered.
JWTs are usually signed using a secret (HMAC) or a public/private key pair (RSA).
Setting Up Flask with JWT
To implement JWT in Flask, you can use libraries like Flask-JWT-Extended, which simplifies token generation and verification.
Step 1: Install the library
bash
pip install Flask-JWT-Extended
Step 2: Initialize the extension
python
from flask import Flask
from flask_jwt_extended import JWTManager
app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'your-secret-key'
jwt = JWTManager(app)
Step 3: Create a login route
python
from flask import request, jsonify
from flask_jwt_extended import create_access_token
@app.route('/login', methods=['POST'])
def login():
username = request.json.get('username')
password = request.json.get('password')
# Dummy user check
if username == 'admin' and password == 'admin':
access_token = create_access_token(identity=username)
return jsonify(access_token=access_token), 200
return jsonify({"msg": "Bad credentials"}), 401
Protecting Routes with JWT
Once a user is authenticated and has a token, you can protect routes using the @jwt_required() decorator.
python
from flask_jwt_extended import jwt_required, get_jwt_identity
@app.route('/protected', methods=['GET'])
@jwt_required()
def protected():
current_user = get_jwt_identity()
return jsonify(logged_in_as=current_user), 200
In the frontend or API client, you’ll send the token in the Authorization header:
makefile
Authorization: Bearer <your_token_here>
Role-Based Authorization
For more advanced scenarios, such as differentiating access based on roles (admin, user, etc.), include roles in the token:
python
access_token = create_access_token(identity={"username": "admin", "role": "admin"})
Then in protected routes:
python
@jwt_required()
def admin_only():
claims = get_jwt_identity()
if claims['role'] != 'admin':
return jsonify(msg="Admins only!"), 403
return jsonify(msg="Welcome, admin.")
Token Expiration and Refreshing
JWTs can be set to expire. You can configure token expiry and even refresh tokens using:
python
from flask_jwt_extended import create_refresh_token
refresh_token = create_refresh_token(identity=username)
Then, allow users to refresh access tokens with a dedicated route.
Conclusion
Implementing JWT in a Flask API offers a robust, stateless solution for handling user authentication and authorization. It reduces the need for session management and scales well with frontend frameworks like React or Vue. Whether you're building a personal project or a production-grade API, integrating JWT ensures your routes are protected and users are securely authenticated.
Learn FullStack Python Training
Read More : Flask API Pagination and Optimized Data Fetching for Scalability
Read More : Flask API Security Best Practices for Fullstack Development
Read More : Fullstack Flask API: Using Redis for API Rate Limiting
Visit Our IHUB Talent Training Institute in Hyderabad
Get Direction
Comments
Post a Comment