Link

Basic Usage

Table of contents

  1. What Is Private Claims?
  2. Configuration
  3. Create Token
  4. Protect Views
  5. Use Token Object
  6. Full Example Code

What Is Private Claims?

claims to share information specific to your application., which might contain application specific information like user_id or permission_level.

Find more about private claims at Auth0

Configuration

We highly recommend to configure JWT.config.private_claim_prefix to avoid collision, such as through namespacing

with JWT.initialize(app) as manager:
    manager.config.private_claim_prefix = "sanic-jwt-extended"

Find more about configuration

Create Token

Both access and refresh token can contain role. you must provide role in string

refresh_token = JWT.create_access_token(identity=username, role="ADMIN")

You can also create token without role.

Find more about creating token

Protect Views

There’s nothing to configurate to get private claims

Use Token Object

propagated Token object contains private claims in Token.private_claims. prefix is not exist on this time.

token.private_claims

Find more about token object


Full Example Code

import uuid

from sanic import Sanic
from sanic.response import json
from sanic.request import Request

from sanic_jwt_extended import JWT, jwt_required
from sanic_jwt_extended.tokens import Token

app = Sanic(__name__)

with JWT.initialize(app) as manager:
    manager.config.secret_key = "secret"
    manager.config.private_claim_prefix = "sanic_jwt_extended"


@app.route("/login", methods=["POST"])
async def login(request: Request):
    username = request.json.get("username", "user")

    access_token = JWT.create_access_token(identity=username, private_claims={"foo": "bar"})

    return json(
        dict(access_token=access_token, refresh_token=refresh_token), status=200
    )


@app.route("/protected", methods=["GET"])
@jwt_required
async def protected(request: Request, token: Token):
    return json(dict(private_claims=token.private_claims))



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