如何在FastAPI中實現請求的身份驗證和授權
如何在FastAPI中實現請求的身份驗證和授權
隨著互聯網的發展,網路安全問題越來越受到關注。在開發Web應用程式時,請求身份驗證和授權是確保應用程式安全的重要環節。本文將介紹如何在FastAPI框架中實現請求的身份驗證和授權。
FastAPI是一個基於Python的高效能Web框架,它提供了一種簡單而強大的方式來建立Web API。它整合了Pydantic庫和Starlette框架,使得開發過程更加輕鬆和有效率。
- 安裝相依性
首先,我們需要安裝FastAPI和對應的依賴。可以透過以下命令來安裝:
$ pip install fastapi $ pip install uvicorn
- 創建基本應用程式
接下來,我們創建一個簡單的FastAPI應用程序,並添加一些基本的路由和端點。在這個範例中,我們將建立一個名為"app.py"的文件,並將以下程式碼複製到其中:
from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"}
- 新增身份驗證和授權
#接下來,我們將介紹如何使用FastAPI的安全功能來實現請求的身份驗證和授權。我們將使用OAuth2.0作為身份驗證和授權的機制。
首先,我們需要導入相關的模組和類別:
from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from passlib.context import CryptContext
然後,我們建立一個密碼加密上下文:
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
接下來,我們定義一個使用者模型,用於驗證使用者身份:
class User: def __init__(self, username: str, password: str, disabled: bool = False): self.username = username self.password = pwd_context.hash(password) self.disabled = disabled def verify_password(self, password: str): return pwd_context.verify(password, self.password) def get_user(self, username: str): if self.username == username: return self
然後,我們建立一個虛擬資料庫,並添加一些使用者信息,用於測試目的:
fake_db = [ User(username="user1", password="password"), User(username="user2", password="password", disabled=True) ]
接下來,我們定義一個函數來驗證使用者的憑證:
def authenticate_user(username: str, password: str): user = get_user(username) if not user: return False if not user.verify_password(password): return False return user
然後,我們定義一個函數來取得目前使用者:
def get_current_user(token: str = Depends(oauth2_scheme)): credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) user = authenticate_user(token) if not user: raise credentials_exception return user
最後,我們將這些函數應用到FastAPI應用程式:
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token") @app.post("/token") async def login(form_data: OAuth2PasswordRequestForm = Depends()): user = authenticate_user(form_data.username, form_data.password) if not user: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid username or password", headers={"WWW-Authenticate": "Bearer"}, ) return {"access_token": str(user.username), "token_type": "bearer"} @app.get("/items/") async def read_items(current_user: User = Depends(get_current_user)): return {"items": [{"item_id": "Item 1"}, {"item_id": "Item 2"}]}
- #測試應用程式
現在,我們可以運行應用程式並測試它。透過執行以下命令來啟動應用程式:
$ uvicorn app:app --reload
接下來,我們可以使用curl或任何HTTP客戶端工具來測試應用程式。首先,我們需要取得存取權杖:
$ curl --request POST --url http://localhost:8000/token --header 'Content-Type: application/x-www-form-urlencoded' --data 'username=user1&password=password'
收到的回應應該類似於:
{"access_token":"user1","token_type":"bearer"}
然後,我們可以使用得到的存取權杖來存取受限端點:
$ curl --request GET --url http://localhost:8000/items/ --header 'Authorization: Bearer user1'
應該會收到類似如下的回應:
{"items":[{"item_id":"Item 1"},{"item_id":"Item 2"}]}
如此,我們成功地在FastAPI應用程式中實現了請求的身份驗證和授權。
總結:
本文介紹如何在FastAPI框架中實現請求的身份驗證和授權。我們使用了FastAPI的安全功能,並透過OAuth2.0機制來進行身份驗證和授權。透過導入相關的模組和類,建立密碼加密上下文,定義使用者模型和驗證函數,實現了請求的身份驗證功能。最後,我們將這些函數應用到FastAPI應用程式中,並進行了測試。透過這些步驟,我們可以建立一個安全可靠的Web應用程式。
以上是如何在FastAPI中實現請求的身份驗證和授權的詳細內容。更多資訊請關注PHP中文網其他相關文章!

pythonlistscanStoryDatatepe,ArrayModulearRaysStoreOneType,and numpyArraySareSareAraysareSareAraysareSareComputations.1)列出sareversArversAtileButlessMemory-Felide.2)arraymoduleareareMogeMogeNareSaremogeNormogeNoreSoustAta.3)

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

useanArray.ArarayoveralistinpythonwhendeAlingwithHomoGeneData,performance-Caliticalcode,orinterfacingwithccode.1)同質性data:arraysSaveMemorywithTypedElements.2)績效code-performance-calitialcode-calliginal-clitical-clitical-calligation-Critical-Code:Arraysofferferbetterperbetterperperformanceformanceformancefornallancefornalumericalical.3)

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactsperformance.2)listssdonotguaranteeconecontanttanttanttanttanttanttanttanttanttimecomplecomecomplecomecomecomecomecomecomplecomectacccesslectaccesslecrectaccesslerikearraysodo。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Dreamweaver Mac版
視覺化網頁開發工具

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器