fastapi+token
时间: 2023-12-14 18:04:30 浏览: 145
Fastapi
以下是使用FastAPI和Token进行身份验证的示例代码:
```python
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
# 模拟用户
fake_users_db = {
"johndoe": {
"username": "johndoe",
"full_name": "John Doe",
"email": "johndoe@example.com",
"hashed_password": "fakehashedsecret",
"disabled": False,
},
"alice": {
"username": "alice",
"full_name": "Alice Wonderson",
"email": "alice@example.com",
"hashed_password": "fakehashedsecret2",
"disabled": True,
},
}
# 获取用户信息
def fake_decode_token(token):
user = None
if token == "johndoe":
user = fake_users_db["johndoe"]
return user
# 验证token
async def get_current_user(token: str = Depends(oauth2_scheme)):
user = fake_decode_token(token)
if not user:
raise HTTPException(
status_code=401,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
return user
# 验证用户是否被禁用
async def get_current_active_user(current_user: dict = Depends(get_current_user)):
if current_user["disabled"]:
raise HTTPException(status_code=400, detail="Inactive user")
return current_user
# 登录获取token
@app.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
user_dict = fake_users_db.get(form_data.username)
if not user_dict:
raise HTTPException(status_code=400, detail="Incorrect username or password")
user = UserInDB(**user_dict)
hashed_password = fake_hash_password(form_data.password)
if not hashed_password == user.hashed_password:
raise HTTPException(status_code=400, detail="Incorrect username or password")
return {"access_token": user.username, "token_type": "bearer"}
# 需要验证的路由
@app.get("/users/me")
async def read_users_me(current_user: dict = Depends(get_current_active_user)):
return current_user
```
在上面的代码中,我们使用OAuth2PasswordBearer和OAuth2PasswordRequestForm来实现身份验证。我们还定义了一个模拟用户数据库fake_users_db,以及一些用于验证和获取当前用户的函数。最后,我们定义了一个需要验证的路由,即/users/me,它需要一个有效的token才能访问。
阅读全文