Insert User ClaimsΒΆ

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 fill the user_claims parameter in the create_access_token() and create_refresh_token() and the data can be accessed later in a protected endpoint with jwt_user_claims in the given token argument.

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 sanic import Sanic
from sanic.response import json
from sanic.request import Request
from sanic_jwt_extended import (
    JWTManager,
    jwt_required,
    create_access_token,
    create_refresh_token,
)
import uuid
from sanic_jwt_extended.tokens import Token

app = Sanic(__name__)

# Setup the Sanic-JWT-Extended extension
app.config["JWT_SECRET_KEY"] = "super-secret"  # Change this!
JWTManager(app)

user_claim = {"VERI TAS": "LUX MEA"}


# Provide a method to create access tokens. The create_access_token()
# function is used to actually generate the token, and you can return
# it to the caller however you choose.
@app.route("/login", methods=["POST"])
async def login(request: Request):
    if not request.json:
        return json({"msg": "Missing JSON in request"}, status=400)

    username = request.json.get("username", None)
    password = request.json.get("password", None)
    if not username:
        return json({"msg": "Missing username parameter"}, status=400)
    if not password:
        return json({"msg": "Missing password parameter"}, status=400)

    if username != "test" or password != "test":
        return json({"msg": "Bad username or password"}, status=403)

    # Identity can be any data that is json serializable
    access_token = await create_access_token(
        identity=username, app=request.app, user_claims=user_claim
    )
    return json(dict(access_token=access_token), status=200)


# Protect a view with jwt_required, which requires a valid access token
# in the request to access.
@app.route("/protected", methods=["GET"])
@jwt_required
async def protected(request: Request, token: Token):
    # Access the identity of the current user with get_jwt_identity
    user_claims = token.jwt_user_claims
    return json(dict(data=user_claims))


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