Link

What Is Refresh Token?

Refresh token is a token carries the information necessary to get a new access token.

Find more about refresh token at Auth0

Using Refresh Token

Table of contents

  1. What Is Refresh Token?
  2. Configuration
  3. Create Refresh Token
  4. Protect Views
  5. Full Example Code

Configuration

There’s nothing to configurate to use refresh token.

Create Refresh Token

After JWT initialized and configured. you can create refresh token through JWT.create_refresh_token

refresh_token = JWT.create_refresh_token(identity=username)

Find more about creating token

Protect Views

jwt_required or jwt_optional only accepts access tokens. so you should use refresh_jwt_required to protect view with refresh token

Important

You should specify token keyword argument to view function(method) as same as jwt_required

@app.route("/refresh", methods=["GET"])
@refresh_jwt_required
async def refresh(request: Request, token: Token):
    ...

Find more about protecting views


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, refresh_jwt_required 
from sanic_jwt_extended.tokens import Token

app = Sanic(__name__)


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


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

    access_token = JWT.create_access_token(identity=username)
    refresh_token = JWT.create_refresh_token(identity=username)

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


@app.route("/refresh", methods=["POST"])
@refresh_jwt_required
async def protected(request: Request, token: Token):
    return json({"refresh_token": JWT.create_access_token(identity=token.identity)})



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