如何在FastAPI中使用JWT令牌进行身份验证和授权
简介:
随着Web应用程序的发展,用户身份验证和授权成为了一个至关重要的部分。使用JWT(JSON Web Token)令牌可以方便地实现身份验证和授权功能。 FastAPI是一个基于Python的现代Web框架,它提供了简单易用的功能来处理身份验证和授权。本文将介绍如何在FastAPI中使用JWT令牌进行身份验证和授权。
- 安装依赖库
首先,我们需要安装一些依赖库,包括FastAPI、PyJWT和Passlib。可以使用pip命令进行安装:
pip install fastapi pip install pyjwt pip install passlib
- 生成秘钥
我们需要生成一个用于签署和验证JWT令牌的秘钥。可以使用以下代码生成秘钥:
import secrets secret_key = secrets.token_urlsafe(32)
- 创建用户模型
在FastAPI中,我们需要定义一个用户模型来表示应用程序中的用户。可以使用以下代码创建用户模型:
from pydantic import BaseModel class User(BaseModel): username: str password: str
- 创建路由和处理函数
接下来,我们需要创建路由和处理函数来处理用户的身份验证和授权请求。可以使用以下代码创建路由和处理函数:
from fastapi import FastAPI, HTTPException from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from passlib.context import CryptContext from datetime import datetime, timedelta import jwt app = FastAPI() pwd_context = CryptContext(schemes=["bcrypt"]) security = HTTPBearer() # 模拟数据库中的用户 users_db = { "admin": { "username": "admin", "password": pwd_context.hash("admin123") } } @app.post("/login") def login(user: User): if user.username not in users_db: raise HTTPException(status_code=401, detail="Invalid username") stored_user = users_db[user.username] if not pwd_context.verify(user.password, stored_user["password"]): raise HTTPException(status_code=401, detail="Invalid password") token = generate_token(user.username) return {"access_token": token} def generate_token(username: str) -> str: expiration = datetime.utcnow() + timedelta(minutes=30) payload = {"username": username, "exp": expiration} return jwt.encode(payload, secret_key, algorithm="HS256") @app.get("/users/me") def get_user_profile(credentials: HTTPAuthorizationCredentials = security): token = credentials.credentials try: payload = jwt.decode(token, secret_key, algorithms=["HS256"]) username = payload["username"] if username not in users_db: raise HTTPException(status_code=401, detail="Invalid username") return {"username": username} except jwt.DecodeError: raise HTTPException(status_code=401, detail="Invalid token")
- 测试功能
现在,我们可以使用Postman或其他HTTP客户端工具来测试我们的功能。首先,我们需要使用POST请求发送登录请求,并在请求体中包含用户名和密码。如下所示:
请求URL:http://localhost:8000/login
请求体:
{ "username": "admin", "password": "admin123" }
成功登录后,我们将收到一个包含访问令牌的响应。例如:
{ "access_token": "xxxxxxxxxxxxx" }
然后,我们可以使用GET请求发送获取用户资料的请求,将访问令牌作为Authorization头部的Bearer令牌发送。如下所示:
请求URL:http://localhost:8000/users/me
请求头部:Authorization: Bearer xxxxxxxxxxxxx
如果令牌验证成功,响应将返回一个包含用户名的JSON对象。例如:
{ "username": "admin" }
结束语:
本文介绍了如何在FastAPI中使用JWT令牌进行身份验证和授权。通过使用PyJWT库,我们生成了JWT令牌,并使用Passlib库进行密码哈希验证。使用这种方法,我们可以轻松地实现用户身份验证和授权功能,从而保护我们的Web应用程序。
以上是如何在FastAPI中使用JWT令牌进行身份验证和授权的详细内容。更多信息请关注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.ArarayoveralistinpythonwhendeAlingwithHomeSdata,performance-Caliticalcode,orinterFacingWithCcccode.1)同质性data:arrayssavememorywithtypedelements.2)绩效code-performance-clitionalcode-clitadialcode-critical-clitical-clitical-clitical-clitaine code:araysofferferbetterperperperformenterperformanceformanceformancefornalumericalicalialical.3)

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactssperformance.2)listssdonotguaranteeconeeconeconstanttanttanttanttanttanttanttanttimecomplecomecomecomplecomecomecomecomecomecomplecomectaccesslikearrikearraysodo。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Atom编辑器mac版下载
最流行的的开源编辑器

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

Dreamweaver CS6
视觉化网页开发工具

SublimeText3汉化版
中文版,非常好用

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中