FastAPI JWT实现配置的完整指南【免费下载链接】fastapiFastAPI framework, high performance, easy to learn, fast to code, ready for production项目地址: https://gitcode.com/GitHub_Trending/fa/fastapiFastAPI是一个高性能、易于学习、快速编码且可用于生产环境的现代API框架。本文将详细介绍如何在FastAPI中实现JWTJSON Web Token认证配置帮助你快速构建安全的API服务。什么是JWT认证JWTJSON Web Token是一种紧凑且自包含的方式用于在各方之间安全地传输信息作为JSON对象。它可以通过数字签名验证信息的完整性常被用于身份验证和信息交换。在FastAPI中集成JWT认证可以有效保护API端点确保只有授权用户才能访问。准备工作在开始配置JWT之前确保你已经安装了必要的依赖包。FastAPI的JWT实现通常需要PyJWT和python-multipart等包。你可以通过以下命令安装pip install fastapi uvicorn pyjwt python-multipartJWT配置步骤1. 设置密钥和算法首先需要定义一个密钥SECRET_KEY和使用的加密算法如HS256。密钥应该是一个强随机字符串你可以使用openssl命令生成openssl rand -hex 32在代码中我们可以这样定义SECRET_KEY 09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7 ALGORITHM HS256 ACCESS_TOKEN_EXPIRE_MINUTES 302. 创建令牌模型和用户模型接下来我们需要定义Pydantic模型来表示令牌和用户信息。这些模型将用于数据验证和序列化from pydantic import BaseModel class Token(BaseModel): access_token: str token_type: str class TokenData(BaseModel): username: str | None None scopes: list[str] [] class User(BaseModel): username: str email: str | None None full_name: str | None None disabled: bool | None None class UserInDB(User): hashed_password: str3. 实现令牌创建和验证函数我们需要编写函数来创建JWT令牌和验证令牌。创建令牌时需要设置过期时间并使用密钥和算法进行签名from datetime import datetime, timedelta, timezone import jwt def create_access_token(data: dict, expires_delta: timedelta | None None): to_encode data.copy() if expires_delta: expire datetime.now(timezone.utc) expires_delta else: expire datetime.now(timezone.utc) timedelta(minutes15) to_encode.update({exp: expire}) encoded_jwt jwt.encode(to_encode, SECRET_KEY, algorithmALGORITHM) return encoded_jwt验证令牌时需要解码令牌并检查其有效性from jwt.exceptions import InvalidTokenError async def get_current_user(token: str Depends(oauth2_scheme)): credentials_exception HTTPException( status_codestatus.HTTP_401_UNAUTHORIZED, detailCould not validate credentials, headers{WWW-Authenticate: Bearer}, ) try: payload jwt.decode(token, SECRET_KEY, algorithms[ALGORITHM]) username: str payload.get(sub) if username is None: raise credentials_exception token_data TokenData(usernameusername) except InvalidTokenError: raise credentials_exception user get_user(fake_users_db, usernametoken_data.username) if user is None: raise credentials_exception return user4. 设置OAuth2密码流FastAPI提供了OAuth2PasswordBearer来处理基于密码的认证流程。我们需要配置令牌URL和作用域from fastapi.security import OAuth2PasswordBearer oauth2_scheme OAuth2PasswordBearer( tokenUrltoken, scopes{me: Read information about the current user., items: Read items.}, )5. 创建登录端点实现一个登录端点用于验证用户凭据并返回JWT令牌from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordRequestForm app.post(/token, response_modelToken) async def login_for_access_token(form_data: OAuth2PasswordRequestForm Depends()): user authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( status_codestatus.HTTP_401_UNAUTHORIZED, detailIncorrect username or password, headers{WWW-Authenticate: Bearer}, ) access_token_expires timedelta(minutesACCESS_TOKEN_EXPIRE_MINUTES) access_token create_access_token( data{sub: user.username, scope: .join(form_data.scopes)}, expires_deltaaccess_token_expires, ) return {access_token: access_token, token_type: bearer}保护API端点配置好JWT后我们可以使用依赖项来保护API端点确保只有携带有效令牌的用户才能访问app.get(/users/me/, response_modelUser) async def read_users_me(current_user: User Depends(get_current_active_user)): return current_user app.get(/users/me/items/) async def read_own_items( current_user: User Security(get_current_active_user, scopes[items]), ): return [{item_id: Foo, owner: current_user.username}]测试JWT认证FastAPI自动生成的Swagger UI可以方便地测试JWT认证。你可以访问http://127.0.0.1:8000/docs使用登录端点获取令牌然后在其他端点的授权字段中输入令牌进行测试。总结通过以上步骤你已经成功在FastAPI中配置了JWT认证。JWT提供了一种安全、高效的方式来保护API端点确保只有授权用户才能访问。FastAPI的设计使得JWT集成变得简单直观同时提供了强大的类型提示和自动文档功能。如果你想深入了解更多细节可以参考项目中的示例代码docs_src/security/tutorial005_py310.py。这个示例包含了完整的JWT实现包括用户认证、令牌创建和端点保护等功能。现在你可以开始构建自己的安全FastAPI应用了【免费下载链接】fastapiFastAPI framework, high performance, easy to learn, fast to code, ready for production项目地址: https://gitcode.com/GitHub_Trending/fa/fastapi创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
FastAPI JWT:实现配置的完整指南
FastAPI JWT实现配置的完整指南【免费下载链接】fastapiFastAPI framework, high performance, easy to learn, fast to code, ready for production项目地址: https://gitcode.com/GitHub_Trending/fa/fastapiFastAPI是一个高性能、易于学习、快速编码且可用于生产环境的现代API框架。本文将详细介绍如何在FastAPI中实现JWTJSON Web Token认证配置帮助你快速构建安全的API服务。什么是JWT认证JWTJSON Web Token是一种紧凑且自包含的方式用于在各方之间安全地传输信息作为JSON对象。它可以通过数字签名验证信息的完整性常被用于身份验证和信息交换。在FastAPI中集成JWT认证可以有效保护API端点确保只有授权用户才能访问。准备工作在开始配置JWT之前确保你已经安装了必要的依赖包。FastAPI的JWT实现通常需要PyJWT和python-multipart等包。你可以通过以下命令安装pip install fastapi uvicorn pyjwt python-multipartJWT配置步骤1. 设置密钥和算法首先需要定义一个密钥SECRET_KEY和使用的加密算法如HS256。密钥应该是一个强随机字符串你可以使用openssl命令生成openssl rand -hex 32在代码中我们可以这样定义SECRET_KEY 09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7 ALGORITHM HS256 ACCESS_TOKEN_EXPIRE_MINUTES 302. 创建令牌模型和用户模型接下来我们需要定义Pydantic模型来表示令牌和用户信息。这些模型将用于数据验证和序列化from pydantic import BaseModel class Token(BaseModel): access_token: str token_type: str class TokenData(BaseModel): username: str | None None scopes: list[str] [] class User(BaseModel): username: str email: str | None None full_name: str | None None disabled: bool | None None class UserInDB(User): hashed_password: str3. 实现令牌创建和验证函数我们需要编写函数来创建JWT令牌和验证令牌。创建令牌时需要设置过期时间并使用密钥和算法进行签名from datetime import datetime, timedelta, timezone import jwt def create_access_token(data: dict, expires_delta: timedelta | None None): to_encode data.copy() if expires_delta: expire datetime.now(timezone.utc) expires_delta else: expire datetime.now(timezone.utc) timedelta(minutes15) to_encode.update({exp: expire}) encoded_jwt jwt.encode(to_encode, SECRET_KEY, algorithmALGORITHM) return encoded_jwt验证令牌时需要解码令牌并检查其有效性from jwt.exceptions import InvalidTokenError async def get_current_user(token: str Depends(oauth2_scheme)): credentials_exception HTTPException( status_codestatus.HTTP_401_UNAUTHORIZED, detailCould not validate credentials, headers{WWW-Authenticate: Bearer}, ) try: payload jwt.decode(token, SECRET_KEY, algorithms[ALGORITHM]) username: str payload.get(sub) if username is None: raise credentials_exception token_data TokenData(usernameusername) except InvalidTokenError: raise credentials_exception user get_user(fake_users_db, usernametoken_data.username) if user is None: raise credentials_exception return user4. 设置OAuth2密码流FastAPI提供了OAuth2PasswordBearer来处理基于密码的认证流程。我们需要配置令牌URL和作用域from fastapi.security import OAuth2PasswordBearer oauth2_scheme OAuth2PasswordBearer( tokenUrltoken, scopes{me: Read information about the current user., items: Read items.}, )5. 创建登录端点实现一个登录端点用于验证用户凭据并返回JWT令牌from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import OAuth2PasswordRequestForm app.post(/token, response_modelToken) async def login_for_access_token(form_data: OAuth2PasswordRequestForm Depends()): user authenticate_user(fake_users_db, form_data.username, form_data.password) if not user: raise HTTPException( status_codestatus.HTTP_401_UNAUTHORIZED, detailIncorrect username or password, headers{WWW-Authenticate: Bearer}, ) access_token_expires timedelta(minutesACCESS_TOKEN_EXPIRE_MINUTES) access_token create_access_token( data{sub: user.username, scope: .join(form_data.scopes)}, expires_deltaaccess_token_expires, ) return {access_token: access_token, token_type: bearer}保护API端点配置好JWT后我们可以使用依赖项来保护API端点确保只有携带有效令牌的用户才能访问app.get(/users/me/, response_modelUser) async def read_users_me(current_user: User Depends(get_current_active_user)): return current_user app.get(/users/me/items/) async def read_own_items( current_user: User Security(get_current_active_user, scopes[items]), ): return [{item_id: Foo, owner: current_user.username}]测试JWT认证FastAPI自动生成的Swagger UI可以方便地测试JWT认证。你可以访问http://127.0.0.1:8000/docs使用登录端点获取令牌然后在其他端点的授权字段中输入令牌进行测试。总结通过以上步骤你已经成功在FastAPI中配置了JWT认证。JWT提供了一种安全、高效的方式来保护API端点确保只有授权用户才能访问。FastAPI的设计使得JWT集成变得简单直观同时提供了强大的类型提示和自动文档功能。如果你想深入了解更多细节可以参考项目中的示例代码docs_src/security/tutorial005_py310.py。这个示例包含了完整的JWT实现包括用户认证、令牌创建和端点保护等功能。现在你可以开始构建自己的安全FastAPI应用了【免费下载链接】fastapiFastAPI framework, high performance, easy to learn, fast to code, ready for production项目地址: https://gitcode.com/GitHub_Trending/fa/fastapi创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考