我对 python 中的 FastAPI 有点陌生。我正在构建一个需要具有基于 JWT 令牌的授权的 API 后端框架。现在,我知道如何生成 JWT 令牌,但不确定如何将其与 Python 中快速 api 中的 API 方法集成。任何指针将不胜感激。
原文由 Aditya Bhattacharya 发布,翻译遵循 CC BY-SA 4.0 许可协议
我对 python 中的 FastAPI 有点陌生。我正在构建一个需要具有基于 JWT 令牌的授权的 API 后端框架。现在,我知道如何生成 JWT 令牌,但不确定如何将其与 Python 中快速 api 中的 API 方法集成。任何指针将不胜感激。
原文由 Aditya Bhattacharya 发布,翻译遵循 CC BY-SA 4.0 许可协议
我发现可以对已接受的答案进行某些改进:
get_token_auth_header
。此外,关于身份验证,生成的文档最终变得非常清晰和解释:JOSEError
的后代的异常,并打印它们的消息,避免捕获特定异常并编写自定义消息示例片段:哪里…
/endpoints
- hello.py
- __init__.p
dependency.py
main.py
# dependency.py script
from jose import jwt
from jose.exceptions import JOSEError
from fastapi import HTTPException, Depends
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
security = HTTPBearer()
async def has_access(credentials: HTTPAuthorizationCredentials= Depends(security)):
"""
Function that is used to validate the token in the case that it requires it
"""
token = credentials.credentials
try:
payload = jwt.decode(token, key='secret', options={"verify_signature": False,
"verify_aud": False,
"verify_iss": False})
print("payload => ", payload)
except JOSEError as e: # catches any exception
raise HTTPException(
status_code=401,
detail=str(e))
# main.py script
from fastapi import FastAPI, Depends
from endpoints import hello
from dependency import has_access
app = FastAPI()
# routes
PROTECTED = [Depends(has_access)]
app.include_router(
hello.router,
prefix="/hello",
dependencies=PROTECTED
)
# hello.py script
from fastapi import APIRouter
router = APIRouter()
@router.get("")
async def say_hi(name: str):
return "Hi " + name
通过利用所有提到的功能,您最终可以超快地构建具有安全性的 API :)
原文由 onofricamila 发布,翻译遵循 CC BY-SA 4.0 许可协议
2 回答5.2k 阅读✓ 已解决
2 回答1.2k 阅读✓ 已解决
5 回答2.4k 阅读
4 回答1.5k 阅读✓ 已解决
3 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
2 回答919 阅读✓ 已解决
在朋友和同事的帮助下,我解决了这个问题,并想与社区分享这个解决方案。这是现在的样子:
Python代码—-
我希望社区能从中受益!