Storing Data in Access TokensΒΆ

You may want to store additional information in the access token which you could later access in the protected views. This can be done with the user_claims_loader() decorator, and the data can be accessed later in a protected endpoint with the get_jwt_claims() function.

Storing data in an access token can be good for performance. If you store data in the token, you wont need to look it up from disk next time you need it in a protected endpoint. However, you should take care what data you put in the token. Any data in the access token can be trivially viewed by anyone who can read the token. Do not store sensitive information in access tokens!

from quart import Quart, jsonify, request
from quart_jwt_extended import (
    JWTManager,
    jwt_required,
    create_access_token,
    get_jwt_claims,
)

app = Quart(__name__)

app.config["JWT_SECRET_KEY"] = "super-secret"  # Change this!
jwt = JWTManager(app)


# Using the user_claims_loader, we can specify a method that will be
# called when creating access tokens, and add these claims to the said
# token. This method is passed the identity of who the token is being
# created for, and must return data that is json serializable
@jwt.user_claims_loader
def add_claims_to_access_token(identity):
    return {"hello": identity, "foo": ["bar", "baz"]}


@app.route("/login", methods=["POST"])
async def login():
    username = (await request.get_json()).get("username", None)
    password = (await request.get_json()).get("password", None)
    if username != "test" or password != "test":
        return {"msg": "Bad username or password"}, 401

    ret = {"access_token": create_access_token(username)}
    return ret, 200


# In a protected view, get the claims you added to the jwt with the
# get_jwt_claims() method
@app.route("/protected", methods=["GET"])
@jwt_required
async def protected():
    claims = get_jwt_claims()
    return {"hello_is": claims["hello"], "foo_is": claims["foo"]}, 200


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