如何在FastAPI中实现请求的身份验证和授权

2023年 8月 8日 33.7k 0

如何在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中实现请求的身份验证和授权的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

    相关文章

    JavaScript2024新功能:Object.groupBy、正则表达式v标志
    PHP trim 函数对多字节字符的使用和限制
    新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
    使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
    为React 19做准备:WordPress 6.6用户指南
    如何删除WordPress中的所有评论

    发布评论