gpt4 book ai didi

python - 如何使用 HTTP Digest 进行身份验证?

转载 作者:行者123 更新时间:2023-12-04 17:20:44 29 4
gpt4 key购买 nike

我目前正在使用基本身份验证,关注 this tutorial :

import secrets

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

http_basic = HTTPBasic()

def authorize_basic(credentials: HTTPBasicCredentials = Depends(http_basic)):
correct_username = secrets.compare_digest(credentials.username, "test")
correct_password = secrets.compare_digest(credentials.password, "test")
if not (correct_username and correct_password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Basic"},
)

@app.get("/auth/", dependencies=[Depends(authorize_basic)])
def auth():
return {"success": "true"}
如何改用 HTTPDigest?

最佳答案

我知道这个问题很久以前就有人问过了,但是这个 example来自 FastAPI 测试套件展示了如何做到这一点。
您可以按如下方式重写上面的示例:

import base64
import secrets

from fastapi import Depends, FastAPI, HTTPException, Security, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPDigest

http_digest = HTTPDigest()

app = FastAPI()


def authorize_digest(credentials: HTTPAuthorizationCredentials = Security(http_digest)):
# Credentials returns the token as string.
incoming_token = credentials.credentials

# Let's say you want to generate the digest token from username and pass.
expected_username = "test"
expected_password = "test"

# Digest tokens are encoded via base64 encoding algo.
expected_token = base64.standard_b64encode(
bytes(f"{expected_username}:{expected_password}", encoding="UTF-8"),
)

correct_token = secrets.compare_digest(
bytes(incoming_token, encoding="UTF-8"),
expected_token,
)
if not correct_token:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect digest token",
headers={"WWW-Authenticate": "Digest"},
)


@app.get("/auth/", dependencies=[Depends(authorize_digest)])
def auth():
return {"success": "true"}

您可以使用 shell 中的用户名和密码获取 token (假设您使用的是 Unix-y 系统):
python -c 'import base64; h = base64.urlsafe_b64encode(b"test:test"); print(h)'
这假设您的用户名和密码都是 test .它将打印以下内容:
b'dGVzdDp0ZXN0'
您可以使用此 token 并通过 curl 向此 API 发送请求:
curl -X 'GET' 'http://localhost:5000/auth/' \
-H 'accept: application/json' \
-H "Authorization: Digest dGVzdDp0ZXN0" \
-H 'Content-Type: application/json' \

这将打印出成功响应:
{"success":"true"}

关于python - 如何使用 HTTP Digest 进行身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66332049/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com