fastapi-learning-notes/codes/ch01/main.py at master · Relph1119/fastapi-learning-notes · GitHub
1、Cookie的作用
Cookie可以充當用戶認證的令牌,使得用戶在首次登錄后無需每次手動輸入用戶名和密碼,即可訪問受限資源,直到Cookie過期或被手動清除。
2、查找Cookie
Google Chrome:
- 打開Chrome瀏覽器。
- 右上角點擊三個點形成的菜單圖標,選擇“更多工具” > “開發者工具”(也可以直接按F12或Ctrl+Shift+I快捷鍵)。
- 在開發者工具窗口中,點擊頂部的“Application”選項卡。
- 在左側導航欄,展開“Cookies”部分,選擇您想查看的網站域名。
?3、Cookie代碼
下面這段代碼使用FastAPI框架實現了一個簡單的用戶登錄和用Cookie進行用戶認證。
- 首先定義了一個User模型類,用于表示用戶信息。
- 創建了一個模擬的用戶數據庫fake_users_db,其中包含5個用戶及其密碼。
- 定義了一個active_tokens字典,用于存儲有效的會話令牌及其對應的用戶名。
- get_current_user函數用于驗證Cookie中的會話令牌是否有效。如果有效,則返回對應的用戶名;否則拋出HTTPException,表示無效的會話令牌。
- login路由處理函數用于處理用戶登錄請求。首先驗證用戶憑據是否正確,如果正確,則生成一個隨機的會話令牌,并將其與用戶名關聯起來,存儲在active_tokens中。然后將該令牌設置為Cookie,并返回登錄成功的信息以及相關數據。
- protected_route路由處理函數是一個受保護的路由,只有攜帶有效會話令牌的請求才能訪問。該函數依賴于get_current_user函數來驗證用戶身份,并返回歡迎信息。
最后,在主函數中使用uvicorn啟動FastAPI應用程序。根據不同的模式,可以選擇線上模式或調試模式運行
import secrets
import uvicorn
from fastapi import FastAPI, Depends, Cookie, HTTPException, Response
from pydantic import BaseModelapp = FastAPI()# 用戶模型
class User(BaseModel):username: strpassword: str# 模擬的用戶數據庫,現在包含5個用戶
fake_users_db = {"john_doe": {"username": "john_doe", "password": "secret_john"},"jane_smith": {"username": "jane_smith", "password": "secret_jane"},"alice": {"username": "alice", "password": "secret_alice"},"bob": {"username": "bob", "password": "secret_bob"},"charlie": {"username": "charlie", "password": "secret_charlie"}
}# 假設這是存儲token與其對應用戶的簡單字典
active_tokens = {}def get_current_user(session_token: str = Cookie(None)):"""驗證Cookie中的session_token是否有效,這里是簡化的版本,實際應用中應該有更安全的驗證機制。"""user = active_tokens.get(session_token)if user is not None:return userelse:raise HTTPException(status_code=401, detail="Invalid session token")@app.post("/login")
async def login(response: Response, user: User):if user.username in fake_users_db and user.password == fake_users_db[user.username]["password"]:token = secrets.token_hex(16)active_tokens[token] = user.username # 將生成的token與用戶名關聯起來print("active_tokens:", active_tokens)response.set_cookie(key="session_token", value=token, max_age=60 * 60 * 24)return {"username": user.username,"password": user.password,"token": token,"active_tokens": active_tokens,"message": f"Login successful for user {user.username}"}else:raise HTTPException(status_code=401, detail="Incorrect username or password")@app.get("/protected-route")
async def protected_route(user: str = Depends(get_current_user)):"""受保護的路由,只有攜帶有效Cookie的請求才能訪問"""return {"message": f"Welcome back, {user}!"}# 主函數,用于啟動FastAPI應用程序
if __name__ == "__main__":## 線上模式# uvicorn.run("abr_server:app", host="0.0.0.0", port = 1218)## debug 模式uvicorn.run("test5:app", host="0.0.0.0", port=1220, reload=True)