FastAPI系列:HttpBasic基本认证

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)

posted @ 2024-02-28 19:09  我在路上回头看  阅读(56)  评论(0编辑  收藏  举报