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