python fastapi接口鉴权方法
时间: 2023-07-28 08:10:47 浏览: 389
FastAPI支持基于Bearer Token的鉴权方法,可以使用FastAPI自带的Depends函数结合PyJWT库实现。
以下是一个示例代码:
```python
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
import jwt
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def verify_token(token: str):
try:
payload = jwt.decode(token, "secret_key", algorithms=["HS256"])
username = payload.get("sub")
if username is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
except jwt.exceptions.DecodeError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
def get_current_user(token: str = Depends(oauth2_scheme)):
verify_token(token)
return token
@app.get("/protected")
async def protected_route(token: str = Depends(oauth2_scheme)):
return {"token": token}
```
在这个示例中,verify_token函数用于验证JWT Token的有效性,get_current_user函数用于获取当前用户信息,protected_route函数需要鉴权才能访问。在访问protected_route时,会自动调用get_current_user函数进行鉴权。如果鉴权失败,会返回401 Unauthorized错误。
阅读全文