首页 > 其他分享 >FastAPI系列:jwt认证

FastAPI系列:jwt认证

时间:2024-02-28 19:13:59浏览次数:20  
标签:__ jose python FastAPI jwt 认证 token data

jwt认证

1.头部Header,主要是对jwt元数据的描述

{
    'alg': 'HS256',
    'typ': 'JWT'
}

2.载荷playload,主要包含jwt信息需要传递的主体数据

{
    'iss': 'jack', # 由jwt签发
    'sub': 'jack', # 该jwt面向的用户组,也称为主题
    'aud': 'jack', # 由谁来接收jwt信息
    'iat': 'xxxxxx', # jwt的签发时间
    'nbf': 'xxxxxx', # jwt的生效时间
    'exp': 'xxxxxx', # jwt的过期时间,unix时间戳
    'jti': 'xxxxxx' # jwt的唯一身份标识
}

3.密钥
4.示例

# 推荐使用python-jose
pip install python-jose

# python-jose的不同加密库
python-jose 默认的方式,使用python-rsa和python-ecdsa进行加密和解密
python-jose[cryptography] 使用cryptography加解密库
python-jose[pycryptodome] 使用pycryptodome加解密库
python-jose[pycrypto] 使用pycrypto加解密库 

# 使用
from datetime import datetime, timedelta
from jose import jwt 
SECRET_KEY = 'secret'  # 可以使用 openssl rand -hex 32 生成
ALGORITHM = 'HS256'
ACCESS_TOKEN_EXPIRE_MINUTES = 30

class TokenUtils:
    @staticmethod
    def token_encode(data):
        return jwt.encode(data, SECRET_KEY, algorithm=ALGORITHM)
    
    @staticmethod
    def token_decode(token):
        return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
    

data = {
    'name': 'admin',
    'exp': datetime.utcnow() + timedelta(minutes=5)
}

if __name__ == '__main__':
    token = TokenUtils.token_encode(data=data)
    print(token)
    
    playload = TokenUtils.token_decode(token=token)
    print(playload)

标签:__,jose,python,FastAPI,jwt,认证,token,data
From: https://www.cnblogs.com/weiweivip666/p/18041467

相关文章

  • FastAPI系列:异步redis
    aioredisofficialwebsiteInstallpipinstallaioredisConnecttoredisfromfastapiimportFastAPIimportaioredisapp=FastAPI()@app.on_event('startup')asyncdefstartup_event():#创建的是线程池对象,默认返回的结果为bytes类型,设置decode_responses表......
  • FastAPI系列:fastapi定制的数据库操作库sqlmodel
    官网sqlmodel安装#安装sqlmodel会自动安装pydantic和sqlalchemypipinstallsqlmodel使用#步骤1,创建sqlmodel引擎fromsqlmodelimportcreate_engine#driver://用户名:密码@ip/数据库engine=create_engine("mysql+mysqldb://root:123456@localhost/api")#步骤......
  • FastAPI系列:自定义认证
    fromtypingimportOptional,TuplefromfastapiimportFastAPI,RequestfrompydanticimportBaseModel#通过starlette.authentication导入AuthenticationBackendfromstarlette.authenticationimportAuthenticationBackend,AuthenticationError,AuthCredentials,S......
  • FastAPI系列:依赖注入
    函数式依赖项fromfastapiimportFastAPIfromfastapiimportQuery,Dependsfromfastapi.exceptionsimportHTTPExceptionapp=FastAPI()defusername_check(username:str=Query(...)):ifusername!='zhong':raiseHTTPException(status_code......
  • FastAPI系列:环境配置读取
    依赖包pipinstallpython-dotenv使用#.env文件ADMIN_EMAIL="[email protected]"APP_NAME="ChimichangApp"#config.pyfrompydantic_settingsimportBaseSettingsclassSettings(BaseSettings):app_name:str="AwesomeAPI"......
  • FastAPI系列:后台任务进程
    注:后台任务应附加到响应中,并且仅在发送响应后运行用于将单个后台任务添加到响应中fromfastapiimportFastAPIfromfastapi.responsesimportJSONResponsefromstarlette.backgroundimportBackgroundTaskfrompydanticimportBaseModelapp=FastAPI()classUser(B......
  • FastAPI系列:中间件
    中间件介绍中间件是一个函数,它在每个请求被特定的路径操作处理之前,以及在每个响应返回之前工作装饰器版中间件1.必须使用装饰器@app.middleware("http"),且middleware_type必须为http2.中间件参数:request,call_next,且call_next它将接收request作为参数@app.middleware("h......
  • FastAPI系列:模型用法
    模型基本用法frompydanticimportBaseModelclassItem(BaseModel):#通过继承BaseModelname:strprice:floatis_offer:Union[bool,None]=None常用的模型属性和方法dict()#将数据模型的字段和值封装成字典json()#将数据模型的字段和值封装成json格......
  • FastAPI系列:上传文件File和UploadFile
    上传文件#file仅适用于小文件@app.post("/files/")asyncdefcreate_file(file:bytes|None=File(default=None)):ifnotfile:return{"message":"Nofilesent"}else:return{"file_size":len(file)}......
  • FastAPI系列:路径参数额外校验Path
    路径参数额外校验PathfromfastapiimportPathapp=FastAPI()@app.get('/items/{item_id}')asyncdefread_items(item_id:str=Path(default=None,max_length=3,min_length=1,title='theidofitemtoget')):"""def......