搜尋
首頁後端開發Python教學如何在FastAPI中實現請求的身份驗證和授權

如何在FastAPI中實現請求的身份驗證和授權

Jul 29, 2023 pm 04:39 PM
身份驗證 (authentication)授權 (authorization)fastapi中的實作方法 (implementation in fastapi)

如何在FastAPI中實現請求的身份驗證和授權

隨著互聯網的發展,網路安全問題越來越受到關注。在開發Web應用程式時,請求身份驗證和授權是確保應用程式安全的重要環節。本文將介紹如何在FastAPI框架中實現請求的身份驗證和授權。

FastAPI是一個基於Python的高效能Web框架,它提供了一種簡單而強大的方式來建立Web API。它整合了Pydantic庫和Starlette框架,使得開發過程更加輕鬆和有效率。

  1. 安裝相依性

首先,我們需要安裝FastAPI和對應的依賴。可以透過以下命令來安裝:

$ pip install fastapi
$ pip install uvicorn
  1. 創建基本應用程式

接下來,我們創建一個簡單的FastAPI應用程序,並添加一些基本的路由和端點。在這個範例中,我們將建立一個名為"app.py"的文件,並將以下程式碼複製到其中:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}
  1. 新增身份驗證和授權

#接下來,我們將介紹如何使用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"}]}
  1. #測試應用程式

現在,我們可以運行應用程式並測試它。透過執行以下命令來啟動應用程式:

$ 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中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
可以在Python數組中存儲哪些數據類型?可以在Python數組中存儲哪些數據類型?Apr 27, 2025 am 12:11 AM

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

如果您嘗試將錯誤的數據類型的值存儲在Python數組中,該怎麼辦?如果您嘗試將錯誤的數據類型的值存儲在Python數組中,該怎麼辦?Apr 27, 2025 am 12:10 AM

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

Python標準庫的哪一部分是:列表或數組?Python標準庫的哪一部分是:列表或數組?Apr 27, 2025 am 12:03 AM

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

您應該檢查腳本是否使用錯誤的Python版本執行?您應該檢查腳本是否使用錯誤的Python版本執行?Apr 27, 2025 am 12:01 AM

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

在Python陣列上可以執行哪些常見操作?在Python陣列上可以執行哪些常見操作?Apr 26, 2025 am 12:22 AM

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

在哪些類型的應用程序中,Numpy數組常用?在哪些類型的應用程序中,Numpy數組常用?Apr 26, 2025 am 12:13 AM

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

您什麼時候選擇在Python中的列表上使用數組?您什麼時候選擇在Python中的列表上使用數組?Apr 26, 2025 am 12:12 AM

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

所有列表操作是否由數組支持,反之亦然?為什麼或為什麼不呢?所有列表操作是否由數組支持,反之亦然?為什麼或為什麼不呢?Apr 26, 2025 am 12:05 AM

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

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

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

熱工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

SecLists

SecLists

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

mPDF

mPDF

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

SublimeText3 英文版

SublimeText3 英文版

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

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器