Basic UsageΒΆ

In its simplest form, there is not much to using flask_jwt_simple.

from flask import Flask, jsonify, request
from flask_jwt_simple import (
    JWTManager, jwt_required, create_jwt, get_jwt_identity
)

app = Flask(__name__)

# Setup the Flask-JWT-Simple extension
app.config['JWT_SECRET_KEY'] = 'super-secret'  # Change this!
jwt = JWTManager(app)


# Provide a method to create access tokens. The create_jwt()
# function is used to actually generate the token
@app.route('/login', methods=['POST'])
def login():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    params = request.get_json()
    username = params.get('username', None)
    password = params.get('password', None)

    if not username:
        return jsonify({"msg": "Missing username parameter"}), 400
    if not password:
        return jsonify({"msg": "Missing password parameter"}), 400

    if username != 'test' or password != 'test':
        return jsonify({"msg": "Bad username or password"}), 401

    # Identity can be any data that is json serializable
    ret = {'jwt': create_jwt(identity=username)}
    return jsonify(ret), 200


# Protect a view with jwt_required, which requires a valid jwt
# to be present in the headers.
@app.route('/protected', methods=['GET'])
@jwt_required
def protected():
    # Access the identity of the current user with get_jwt_identity
    return jsonify({'hello_from': get_jwt_identity()}), 200

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

To access a jwt_required protected view, all we have to do is send in the JWT with the request. By default, this is done with an authorization header that looks like:

Authorization: Bearer <access_token>

We can see this in action using CURL:

$ curl http://localhost:5000/protected
{
  "msg": "Missing Authorization Header"
}

$ curl -H "Content-Type: application/json" -X POST \
  -d '{"username":"test","password":"test"}' http://localhost:5000/login
{
    "jwt": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MDM1OTk3MTgsImlhdCI6MTUwMzU5NjExOCwibmJmIjoxNTAzNTk2MTE4LCJzdWIiOiJ0ZXN0In0.G2GnN9NgvvmSKgRDGok0OjAyDWkG_qCn4FTxSfPUXDY"
}

$ export ACCESS="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MDM1OTk3MTgsImlhdCI6MTUwMzU5NjExOCwibmJmIjoxNTAzNTk2MTE4LCJzdWIiOiJ0ZXN0In0.G2GnN9NgvvmSKgRDGok0OjAyDWkG_qCn4FTxSfPUXDY"

$ curl -H "Authorization: Bearer $ACCESS" http://localhost:5000/protected
{
  "hello_from": "test"
}

NOTE: Remember to change the JWT_SECRET_KEY on your application, and insure that no one is able to view it. The json web tokens are signed with the secret key, so if someone gets that, they can create arbitrary tokens, and in essence log in as any user.