fastapi_No.22_安全性_HTTPBasic

HTTPBasic认证说明

网站开发中还有一种HTTPBasic认证的方法。它的表现形式就是在访问网站时,网站会跳出一个对话框,需要你输入相应的用户名和密码。只有在用户名和密码都正确的情况下,才能够打开该网页。
如下图,访问这个网站的时候,会跳出一个认证窗口,要求输入用户名和密码。
示意图:
在这里插入图片描述

代码实现

# 导入secrets用于进行字符串比较
import secrets

from fastapi import Depends,FastAPI,HTTPException,status
from fastapi.security import HTTPBasic,HTTPBasicCredentials

app = FastAPI()

# 创建HTTPBasic实例对象,作为依赖项,实现弹窗效果
security = HTTPBasic()
# HTTPBasicCredentials是HTTPBasic()返回类型,包含录入的username和password信息
def get_current_username(credentials:HTTPBasicCredentials=Depends(security)):
    # 对获取的username和password进行utf8编码
    current_username_bytes = credentials.username.encode("utf8")
    username_in_db_bytes = b"fakeuser"
    # 防止黑客攻击,利用secrets的compare_digest方法比较录入值和正确值是否一致
    is_correct_username = secrets.compare_digest(username_in_db_bytes,current_username_bytes)
    if is_correct_username:
        current_pwd_bytes = credentials.password.encode("utf8")
        pwd_in_db_bytes = b"fakepwd"
        is_corrent_pwd = secrets.compare_digest(pwd_in_db_bytes,current_pwd_bytes)
        if is_corrent_pwd:
            return credentials.username
        else:
            raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrent username or pwd",
            headers={"WWW-Authenticate":"Basic"}
        )
    else:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrent username or pwd",
            headers={"WWW-Authenticate":"Basic"}
        )
# 定义需要认证的路径
@app.get("/users/me")
def read_current_user(username:str=Depends(get_current_username)):
    return {
        "username":username
    }
# 定义不需要认证的路径
@app.get("/item/{item_id}")
def get_item(item_id:int):
    return{
        "item_id":item_id
    }

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app='basicAuth:app',host='127.0.0.1',port=8080,reload=True)

测试结果

当录入正确的用户名和密码时得到正确的回复。
在这里插入图片描述
录入错误的用户信息时,产生报错。

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱学习_程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值