基于FastAPI Docs安全登录示例

问题描述 投票:0回答:1

我设法使用在线文档安全部分示例使用 FastAPI 构建了一个登录系统。它或多或少是相同的,除了你必须从 MySql 获取用户。 我有两个问题。 我只能通过 FastAPI Docs 右上角的绿色授权按钮进行授权。

API 登录功能可以使用有效的 jwt,但是...

还给出了一个错误(我猜是由 API 处理的)

(trapped) error reading bcrypt version
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/passlib/handlers/bcrypt.py", line 620, in \_load_backend_mixin
version = \_bcrypt.__about__.__version__
^^^^^^^^^^^^^^^^^
AttributeError: module 'bcrypt' has no attribute '__about__'
INFO:     127.0.0.1:49518 - "POST /login/token HTTP/1.1" 200 OK

然后,当我使用这个依赖于 jwt 的函数时...

@router.get("/users/me/", response_model=schemas.User)
async def read_users_me(
current_user: Annotated\[schemas.User, Depends(get_current_active_user)\]
):
return current_user

我从服务器收到此响应..

{
"detail": "Not authenticated"
}

但是,如果我通过 FastAPI/Swagger Docs Authorize 登录,那么一切正常。 我检查了我的令牌网址,看起来没问题。 有什么想法吗?

我尝试从我的 FastAPI 端创建一个登录端点,如本示例
中所述 但是,我无法让它完全正常工作..

authentication security oauth-2.0 jwt fastapi
1个回答
0
投票

如果您通过 Swagger 登录按钮登录,Swagger 将存储收到的令牌并将其附加到每个请求(在标头中)。

但是,如果您仅使用端点登录(即使您通过 Swagger 文档进行登录),Swagger 不会存储您的令牌并将其附加到每个请求。 Swagger 将只发送登录请求,接收响应并向您显示此响应。

您也可以使用“fetch”进行检查。在浏览器中打开 API 的某个 url,打开开发人员工具、控制台。 调用登录端点并接收令牌(检查登录网址、用户名和密码)

 fetch(
 'http://127.0.0.1:8000/auth/login',
 {
     method: 'POST',
     credentials: "include",
     headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
     body: "username=EMAIL&password=PWD"
 }
 ).then(resp => resp.text()).then(console.log)

然后尝试使用受保护的端点并在标头中发送令牌(用您的令牌替换 TOKEN_RECEIVED_IN_PREVIOUS_STEP)

 fetch(
 'http://127.0.0.1:8000/me',
 {
     method: 'GET',
     credentials: "include",
     headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer TOKEN_RECEIVED_IN_PREVIOUS_STEP' }
 }
 ).then(resp => resp.text()).then(console.log)
© www.soinside.com 2019 - 2024. All rights reserved.