如何在fastapi中使用刷新令牌? [英] How to use refresh token with fastapi?

查看:465
本文介绍了如何在fastapi中使用刷新令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找使用刷新令牌. fastapi 文档提供了一个示例,说明了如何创建具有有限限制的承载令牌寿命,但不刷新令牌.

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.

对于烧瓶,有 flask-jwt-extended ,但没有找到与fastapi类似的东西.

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

任何建议将不胜感激!

推荐答案

您可能想查看 fastapi-jwt-auth .它是受flask-jwt-extended启发的.有一个很好的文档,其中包含有关如何使用刷新令牌的很好的示例.

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.

首先,您需要安装软件包:pip install fastapi-jwt-auth.并配置秘密. 然后在登录名上创建刷新令牌和访问令牌,并将其返回给用户.

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"}

从安全角度来看,这只是一个小例子,您应该在刷新时交换刷新令牌,并将旧令牌列入黑名单.因此,该库提供了装饰器@AuthJWT.token_in_denylist_loader.您可以使用内存数据库来实现黑名单,该数据库将保留无效的令牌,直到到达到期日期.在生产中还要选择一个真正的秘密.

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.

这篇关于如何在fastapi中使用刷新令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆