0
0
FlaskHow-ToBeginner · 4 min read

How to Use flask-jwt-extended for JWT Authentication in Flask

To use flask-jwt-extended, first install and initialize it in your Flask app, then create JWT tokens with create_access_token and protect routes using the @jwt_required() decorator. This library helps you manage JSON Web Tokens easily for user authentication.
📐

Syntax

flask-jwt-extended provides key functions and decorators:

  • JWTManager(app): Initializes JWT support in your Flask app.
  • create_access_token(identity): Creates a JWT token for a user identity.
  • @jwt_required(): Protects routes so only requests with valid JWT tokens can access.
  • get_jwt_identity(): Retrieves the identity from the current JWT token inside protected routes.
python
from flask import Flask, jsonify
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity

app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'your-secret-key'
jwt = JWTManager(app)

@app.route('/login', methods=['POST'])
def login():
    # Normally verify user credentials here
    access_token = create_access_token(identity='user_id')
    return jsonify(access_token=access_token)

@app.route('/protected', methods=['GET'])
@jwt_required()
def protected():
    current_user = get_jwt_identity()
    return jsonify(logged_in_as=current_user)
💻

Example

This example shows a simple Flask app using flask-jwt-extended to create a token on login and protect a route that requires the token.

python
from flask import Flask, jsonify, request
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity

app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'super-secret-key'
jwt = JWTManager(app)

@app.route('/login', methods=['POST'])
def login():
    username = request.json.get('username', None)
    password = request.json.get('password', None)
    if username != 'test' or password != 'test':
        return jsonify({'msg': 'Bad username or password'}), 401
    access_token = create_access_token(identity=username)
    return jsonify(access_token=access_token)

@app.route('/protected', methods=['GET'])
@jwt_required()
def protected():
    current_user = get_jwt_identity()
    return jsonify(logged_in_as=current_user)

if __name__ == '__main__':
    app.run(debug=True)
Output
Running the app and sending POST to /login with JSON {"username": "test", "password": "test"} returns a JSON with an access_token string. Accessing GET /protected with header Authorization: Bearer <access_token> returns {"logged_in_as": "test"}.
⚠️

Common Pitfalls

  • Forgetting to set JWT_SECRET_KEY in app config causes token creation to fail.
  • Not sending the JWT token in the Authorization header with Bearer prefix results in 401 errors.
  • Using @jwt_required() on routes but not initializing JWTManager leads to errors.
  • Trying to get identity outside a protected route causes errors because no token is available.
python
from flask import Flask, jsonify
from flask_jwt_extended import JWTManager, create_access_token, jwt_required

app = Flask(__name__)
# Missing JWT_SECRET_KEY causes error
# app.config['JWT_SECRET_KEY'] = 'secret'

jwt = JWTManager(app)

@app.route('/login')
def login():
    token = create_access_token(identity='user')  # This will raise an error without secret key
    return jsonify(token=token)

@app.route('/protected')
@jwt_required()
def protected():
    return jsonify(msg='Protected')

# Correct way:
# Set JWT_SECRET_KEY in config before creating JWTManager
# Send token in Authorization header as 'Bearer <token>'
📊

Quick Reference

Function/DecoratorPurpose
JWTManager(app)Initialize JWT support in Flask app
create_access_token(identity)Create a JWT token for a user
@jwt_required()Protect routes to require valid JWT token
get_jwt_identity()Get current user identity from token
app.config['JWT_SECRET_KEY']Secret key to sign JWT tokens

Key Takeaways

Always set a strong JWT_SECRET_KEY in your Flask app config before using flask-jwt-extended.
Use create_access_token(identity) to generate tokens after verifying user credentials.
Protect routes with @jwt_required() to ensure only requests with valid tokens can access them.
Retrieve the current user identity inside protected routes with get_jwt_identity().
Send JWT tokens in the Authorization header as 'Bearer ' when calling protected endpoints.