Build a Python REST API with JWT and implement a custom @require_role('admin') decorator that inspects request context, decodes the JWT, verifies the signature, and checks if the roles claim contains admin before executing the route.
Assistant
Providing Python Flask JWT API with role-based decorator
Here's a complete Flask example using PyJWT that implements a @require_role('admin') decorator to verify JWTs, check the "roles" claim for "admin", and protect routes accordingly. It includes token generation, error handling, and usage instructions.
Below is a minimal, self‑contained Flask example using PyJWT to issue and verify JWTs and a @require_role('admin') decorator that:
Reads the bearer token from the Authorization header.
Decodes and verifies the signature of the JWT.
Checks that the roles claim contains "admin".
Only then allows the route to execute; otherwise returns 401/403.
python
# filename: app.py
import datetime
from functools import wraps
import jwt
from flask import Flask, request, jsonify, make_response
app = Flask(__name__)
app.config["SECRET_KEY"] = "replace_with_a_strong_secret" # demo secret
def generate_token(username, roles):
"""
Simple helper to generate a JWT for demonstration.
In a real app, you'd validate the user, etc.
"""
payload = {
"sub": username,
"roles": roles,
"exp": datetime.datetime.utcnow() + datetime.timedelta(hours=1),
"iat": datetime.datetime.utcnow(),
}
token = jwt.encode(payload, app.config["SECRET_KEY"], algorithm="HS256")
# PyJWT 2.x returns a string by default; if bytes, decode
if isinstance(token, bytes):
token = token.decode("utf-8")
return token
def require_role(role_name):
"""
Decorator factory that enforces that a valid JWT is present and that
the given role is in the 'roles' claim.
"""
def decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
# 1) Get Authorization header
auth_header = request.headers.get("Authorization", None)
if not auth_header or not auth_header.startswith("Bearer "):
return make_response(jsonify({"error": "Missing or invalid Authorization header"}), 401)
token = auth_header.split(" ", 1)[1]
# 2) Decode & verify
try:
payload = jwt.decode(token, app.config["SECRET_KEY"], algorithms=["HS256"])
except jwt.ExpiredSignatureError:
return make_response(jsonify({"error": "Token has expired"}), 401)
except jwt.InvalidTokenError:
return make_response(jsonify({"error": "Invalid token"}), 401)
# 3) Check the 'roles' claim
roles_claim = payload.get("roles", [])
if role_name not in roles_claim:
return make_response(jsonify({"error": f"Insufficient role. Required: {role_name}"}), 403)
# Optionally store user info in request context if needed
request.user = payload
# 4) Proceed
return fn(*args, **kwargs)
return wrapper
return decorator
@app.route("/public", methods=["GET"])
def public_route():
return jsonify({"message": "Hello, this is a public endpoint."})
@app.route("/protected/admin", methods=["GET"])
@require_role("admin")
def protected_admin_route():
return jsonify({"message": "Hello Admin! You have access to this route."})
@app.route("/login", methods=["POST"])
def login():
"""
Dummy login that issues a token for demonstration.
Expects JSON with {"username": "...", "roles": ["admin"]} or similar.
"""
data = request.get_json() or {}
username = data.get("username")
roles = data.get("roles", [])
if not username:
return make_response(jsonify({"error": "Missing username"}), 400)
token = generate_token(username, roles)
return jsonify({"token": token})
if __name__ == "__main__":
# Example usage:
# 1) Start the app: python app.py
# 2) Obtain a token with admin role:
# curl -X POST http://localhost:5000/login \
# -H "Content-Type: application/json" \
# -d '{"username": "alice", "roles":["admin"]}'
# 3) Access the protected admin route:
# curl http://localhost:5000/protected/admin \
# -H "Authorization: Bearer <the_token_from_step_2>"
app.run(debug=True)
Quick notes:
Install dependencies:
bash
pip install flask pyjwt
The @require_role decorator verifies the JWT (signature and expiry) and checks for membership in the roles claim.
In production, use a secure SECRET_KEY loaded from environment/config and handle additional claims (issuer, audience, etc.) as needed.