0
0
FlaskHow-ToBeginner · 4 min read

How to Implement JWT Authentication in Flask Quickly

To implement JWT authentication in Flask, use the flask-jwt-extended extension to create and verify tokens easily. Initialize the extension, protect routes with @jwt_required(), and generate tokens on user login with create_access_token().
📐

Syntax

This is the basic pattern to implement JWT auth in Flask using flask-jwt-extended:

  • Import and initialize JWTManager with your Flask app.
  • Create access tokens with create_access_token(identity) after user login.
  • Protect routes by adding the @jwt_required() decorator.
  • Access the current user identity inside protected routes with get_jwt_identity().
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'] = 'your-secret-key'
jwt = JWTManager(app)

@app.route('/login', methods=['POST'])
def login():
    username = request.json.get('username')
    password = request.json.get('password')
    # Validate username and password here
    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()
💻

Example

This example shows a simple Flask app with JWT authentication. Users send their username and password to /login to get a token. Then they use this token to access the protected /protected route.

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)

# Dummy user data
users = {'alice': 'wonderland', 'bob': 'builder'}

@app.route('/login', methods=['POST'])
def login():
    username = request.json.get('username', None)
    password = request.json.get('password', None)
    if not username or not password:
        return jsonify({'msg': 'Missing username or password'}), 400
    if users.get(username) != password:
        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 on http://127.0.0.1:5000/ (Press CTRL+C to quit) # Example requests: # POST /login with JSON {"username": "alice", "password": "wonderland"} # Response: {"access_token": "<token>"} # GET /protected with header Authorization: Bearer <token> # Response: {"logged_in_as": "alice"}
⚠️

Common Pitfalls

  • Not setting JWT_SECRET_KEY in app config causes token creation to fail.
  • Forgetting to decorate protected routes with @jwt_required() leaves them unprotected.
  • Using tokens without the Authorization: Bearer <token> header format will cause authentication errors.
  • Not validating user credentials before creating tokens can lead to security issues.
python
from flask import Flask, jsonify, request
from flask_jwt_extended import JWTManager, create_access_token, jwt_required

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

jwt = JWTManager(app)

@app.route('/login', methods=['POST'])
def login():
    # No user validation here (wrong)
    username = request.json.get('username')
    access_token = create_access_token(identity=username)
    return jsonify(access_token=access_token)

@app.route('/protected', methods=['GET'])
# Missing @jwt_required() decorator (wrong)
def protected():
    return jsonify(message='This should be protected')

if __name__ == '__main__':
    app.run()
📊

Quick Reference

JWT Authentication in Flask Cheat Sheet:

  • app.config['JWT_SECRET_KEY']: Set your secret key for signing tokens.
  • JWTManager(app): Initialize JWT support.
  • create_access_token(identity): Create a JWT token for a user.
  • @jwt_required(): Protect routes that need authentication.
  • get_jwt_identity(): Get the current user's identity inside protected routes.

Key Takeaways

Always set a strong JWT_SECRET_KEY in your Flask app config.
Use @jwt_required() to protect routes that need authentication.
Create tokens with create_access_token() after validating user credentials.
Pass tokens in the Authorization header as Bearer tokens.
Use get_jwt_identity() to access the current user inside protected routes.