How to use refresh token with fastapi?

Viewed 10728

I'm trying to find an example of using the refresh token in fastapi. The fastapi docs provides an example of how to create a bearer token with a limited lifetime but not how to refresh the token.

For flask there is flask-jwt-extended but didn't find something similar for fastapi.

Any suggestions will be appreciated thx!

2 Answers

You might wanna check out fastapi-jwt-auth. It is inspired by flask-jwt-extended. There is a good documentation on how to use the refresh token with good examples.

First you need to install the package: pip install fastapi-jwt-auth. And configure the secret. Then on the login create a refresh token and access token and return it to the user.


from fastapi import FastAPI, Depends, HTTPException
from fastapi_jwt_auth import AuthJWT
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    email: str
    password: str

class Settings(BaseModel):
    authjwt_secret_key: str = "secret"

@AuthJWT.load_config
def get_config():
    return Settings()

@app.post('/login')
def login(user: User, Authorize: AuthJWT = Depends()):
    if user.email != "test@test.com" or user.password != "test":
        raise HTTPException(status_code=401,detail="Incorrect email or password")
    access_token = Authorize.create_access_token(subject=user.email)
    refresh_token = Authorize.create_refresh_token(subject=user.email)
    return {"access_token": access_token, "refresh_token": refresh_token}

In the next step you should create an Endpoint to refresh the access token.

@app.post('/refresh')
def refresh(Authorize: AuthJWT = Depends()):
    Authorize.jwt_refresh_token_required()
    current_user = Authorize.get_jwt_subject()
    new_access_token = Authorize.create_access_token(subject=current_user)
    return {"access_token": new_access_token}

# Example protected Endpoint
@app.get('/hello')
def refresh(Authorize: AuthJWT = Depends()):
    Authorize.jwt_required()
    return {"hello": "world"}

Note this only a small example from a security perspective you should swap the refresh tokens on refresh and blacklist the old token. The library offers therefore the decorator @AuthJWT.token_in_denylist_loader. You could implement the blacklist with an in-memory database that keeps invalidated tokens until the expiry date is reached. Also in production choose a real secret.

I generated my own token, according to the time interval between this request and the last request to determine whether to refresh the token, if the time exceeds the scheduled time to replace the token, while notifying the front-end to save the new token

Related