HttpBasic基本认证
from fastapi import FastAPI, Depends
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.exceptions import HTTPException
from fastapi.responses import PlainTextResponse
from starlette.status import HTTP_401_UNAUTHORIZED
app = FastAPI(
title='HttpBasic基本认证示例',
description='HttpBasic基本认证示例',
version='v1.1.0'
)
security = HTTPBasic()
@app.get('/login')
async def login(credentials: HTTPBasicCredentials = Depends(security)):
# HTTPBasicCredentials对象可以获取到用户名和密码
if credentials.username != 'jack' or credentials.password != '123456':
raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail='用户名或密码错误',headers={'WWW-Authenticate': 'Basic'})
else:
return PlainTextResponse('登录成功')
if __name__ == '__main__':
import uvicorn
uvicorn.run('main:app', host='0.0.0.0', port=8000, reload=True)
标签:__,FastAPI,认证,fastapi,import,HttpBasic
From: https://www.cnblogs.com/weiweivip666/p/18041488