0

如何添加我的用户名和密码并为基本身份验证添加 base64。( https://fastapi.tiangolo.com/tutorial/security/http-basic-auth/ )

我读了很多书,最后我什至用密码(和散列)设置了 OAuth2,用 JWT 令牌设置了承载,但这对我来说太多了,我只需要一个简单的基本身份验证并添加一个小保护就可以了,基本上加个base64。

这个想法是在标题中有这样的东西:

{'Authorization': 'Basic aGVsbG86d29ybGQ='} #hello:world

但是我的知识非常少,我遇到了第一个问题,甚至配置如何使用我自己的用户名和密码:

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

app = FastAPI()

security = HTTPBasic()


@app.get("/users/me")
def read_current_user(credentials: HTTPBasicCredentials = Depends(security)):
    return {"username": credentials.username, "password": credentials.password}

登录

我的问题:

如何选择自己的用户名和密码,然后才能使用 base64 对授权进行编码/解码,以便能够发送到标头,例如:

{'Authorization': 'Basic aGVsbG86d29ybGQ='} #hello:world

4

1 回答 1

3

我没有使用过 FastAPI,但我查看了文档。您在那里提供了以下源代码:

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

app = FastAPI()

security = HTTPBasic()


def get_current_username(credentials: HTTPBasicCredentials = Depends(security)):
    if credentials.username != "foo" or credentials.password != "password":
        raise HTTPException(
            status_code=HTTP_401_UNAUTHORIZED,
            detail="Incorrect email or password",
            headers={"WWW-Authenticate": "Basic"},
        )
    return credentials.username


@app.get("/users/me")
def read_current_user(username: str = Depends(get_current_username)):
    return {"username": username}

所以你要做的就是使用一个Depends对象。这个层次是一个简单的例子,但通常你get_current_username()会做一个数据库查询来检查用户及其对应的密码是否存在。你也可以看看这个 git-repo https://gist.github.com/nilsdebruin/8b36cd98c9949a1a87e3a582f70146f1

我希望这可以帮助你!:)

于 2019-12-18T09:01:55.157 回答