FastAPI 使用JWT认证的中间件

FastAPI 使用JWT认证的中间件 fastapi的中间件还是太少,单独开发JWT需要,starlette本身提供认证相关实现,只需要自定义一个AuthenticationBackend即可,本次我们实现使用中间价方式拆包JWT的令牌,获取payload里面的用户信息 私有定义的payload内容格式如下 { “usid”: “SkDQBhEjUfygRSeEBech”, //UUID Short “uname”: “test user name”, //Username “mid”:”700010001″ // Member ID } 调用代码 app = FastAPI() app.add_middleware(AuthenticationMiddleware,backend=JWTAuthenticationBackend(secret_key=”YOUR_SECRET_KEY”)) 完整的代码 import jwt from starlette.authentication import ( AuthenticationBackend, AuthenticationError, BaseUser, AuthCredentials, UnauthenticatedUser ) class JWTUser(BaseUser): def __init__(self, user_id_short: str, member_number: str, user_name: str,token: str, payload: dict) -> None: self.user_name = user_name …