首页 > 其他分享 >FastAPI系列:自定义认证

FastAPI系列:自定义认证

时间:2024-02-28 18:44:17浏览次数:31  
标签:username return 自定义 FastAPI self 认证 import middleware starlette

from typing import Optional, Tuple

from fastapi import FastAPI, Request
from pydantic import BaseModel
# 通过starlette.authentication导入AuthenticationBackend
from starlette.authentication import AuthenticationBackend, AuthenticationError, AuthCredentials, SimpleUser, requires
from starlette.middleware import Middleware
from starlette.middleware.authentication import AuthenticationMiddleware
from starlette.requests import HTTPConnection

class UserReq(BaseModel):
    username: str
    password: str

class UsernameAuthBackend(AuthenticationBackend):
    keyword = 'bearer'

    def __init__(self, username):
        self.username = username

    async def authenticate(self, request):
        if "Authorization" not in request.headers:
            return

        auth = request.headers["Authorization"]
        print(auth)
        try:
            scheme, username = auth.split()
            if scheme.lower().strip() != self.keyword.strip():
                return
        except:
            raise AuthenticationError('Invalid basic auth credentials')
        if not username == self.username:
            return

        return AuthCredentials(["authenticated"]), SimpleUser(username)


middleware = [Middleware(AuthenticationMiddleware, backend=UsernameAuthBackend("liuwei"))]

app = FastAPI(middleware=middleware)


@requires("authenticated")
@app.get("/login")
def login(user: UserReq, request: Request):
    return user

标签:username,return,自定义,FastAPI,self,认证,import,middleware,starlette
From: https://www.cnblogs.com/weiweivip666/p/18041433

相关文章

  • 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......
  • FastAPI系列:查询字符串参数
    单个查询字符串@app.get('/index/{username}')defindex(username:str,id:int):#id为查询字符串?id=5return{"message":"success","username":username,"id":id}可选的查询字符串参数@app.get('/items/{item_id}......
  • FastAPI系列:APIRouter实例的路由注册
    APIRouter实例的路由注册API端点路由注册大致分为3种:1.基于app实例对象提供的装饰器或函数进行注册2.基于FastAPI提供的APIRouter类的实例对象提供的装饰器或函数进行注册3.通过直接实例化APIRoute对象且添加的方式进行注册路由注册方式基于APIRouter的实例对象实现路由注册......
  • FastAPI系列:mount应用挂载
    mount应用挂载1.创建主app应用对象实例,注册所属的路由信息fromfastapiimportFastAPIfromfastapi.responseimportJSONResponseapp=FastAPI(title='主应用',description='主应用描述',version='v1.0.0')@app.get('/index',summary='首页')......