FastAPI-Cookie

news/2024/7/7 20:59:13 标签: fastapi

fastapi-learning-notes/codes/ch01/main.py at master · Relph1119/fastapi-learning-notes · GitHub

1、Cookie的作用

Cookie可以充当用户认证的令牌,使得用户在首次登录后无需每次手动输入用户名和密码,即可访问受限资源,直到Cookie过期或被手动清除。

2、查找Cookie

Google Chrome:

  1. 打开Chrome浏览器。
  2. 右上角点击三个点形成的菜单图标,选择“更多工具” > “开发者工具”(也可以直接按F12或Ctrl+Shift+I快捷键)。
  3. 在开发者工具窗口中,点击顶部的“Application”选项卡。
  4. 在左侧导航栏,展开“Cookies”部分,选择您想查看的网站域名。


 3、Cookie代码

下面这段代码使用FastAPI框架实现了一个简单的用户登录和用Cookie进行用户认证

  • 首先定义了一个User模型类,用于表示用户信息。
  • 创建了一个模拟的用户数据库fake_users_db,其中包含5个用户及其密码。
  • 定义了一个active_tokens字典,用于存储有效的会话令牌及其对应的用户名。
  • get_current_user函数用于验证Cookie中的会话令牌是否有效。如果有效,则返回对应的用户名;否则抛出HTTPException,表示无效的会话令牌。
  • login路由处理函数用于处理用户登录请求。首先验证用户凭据是否正确,如果正确,则生成一个随机的会话令牌,并将其与用户名关联起来,存储在active_tokens中。然后将该令牌设置为Cookie,并返回登录成功的信息以及相关数据。
  • protected_route路由处理函数是一个受保护的路由,只有携带有效会话令牌的请求才能访问。该函数依赖于get_current_user函数来验证用户身份,并返回欢迎信息。

最后,在主函数中使用uvicorn启动FastAPI应用程序。根据不同的模式,可以选择线上模式或调试模式运行

import secrets
import uvicorn
from fastapi import FastAPI, Depends, Cookie, HTTPException, Response
from pydantic import BaseModel

app = FastAPI()


# 用户模型
class User(BaseModel):
    username: str
    password: str


# 模拟的用户数据库,现在包含5个用户
fake_users_db = {
    "john_doe": {"username": "john_doe", "password": "secret_john"},
    "jane_smith": {"username": "jane_smith", "password": "secret_jane"},
    "alice": {"username": "alice", "password": "secret_alice"},
    "bob": {"username": "bob", "password": "secret_bob"},
    "charlie": {"username": "charlie", "password": "secret_charlie"}
}

# 假设这是存储token与其对应用户的简单字典
active_tokens = {}


def get_current_user(session_token: str = Cookie(None)):
    """
    验证Cookie中的session_token是否有效,这里是简化的版本,实际应用中应该有更安全的验证机制。
    """
    user = active_tokens.get(session_token)
    if user is not None:
        return user
    else:
        raise HTTPException(status_code=401, detail="Invalid session token")


@app.post("/login")
async def login(response: Response, user: User):
    if user.username in fake_users_db and user.password == fake_users_db[user.username]["password"]:
        token = secrets.token_hex(16)
        active_tokens[token] = user.username  # 将生成的token与用户名关联起来
        print("active_tokens:", active_tokens)
        response.set_cookie(key="session_token", value=token, max_age=60 * 60 * 24)
        return {"username": user.username,
                "password": user.password,
                "token": token,
                "active_tokens": active_tokens,
                "message": f"Login successful for user {user.username}"}

    else:
        raise HTTPException(status_code=401, detail="Incorrect username or password")


@app.get("/protected-route")
async def protected_route(user: str = Depends(get_current_user)):
    """
    受保护的路由,只有携带有效Cookie的请求才能访问
    """
    return {"message": f"Welcome back, {user}!"}


# 主函数,用于启动FastAPI应用程序
if __name__ == "__main__":
    ## 线上模式
    # uvicorn.run("abr_server:app", host="0.0.0.0", port = 1218)

    ## debug 模式
    uvicorn.run("test5:app", host="0.0.0.0", port=1220, reload=True)


http://www.niftyadmin.cn/n/5535298.html

相关文章

设计模式-结构型-08-组合模式

文章目录 1、学校院系展示需求2、组合模式基本介绍3、组合模式示例3.1、 解决学校院系展示(透明模式1)3.2、高考的科目(透明模式2)3.3、高考的科目(安全组合模式) 4、JDK 源码分析5、注意事项和细节 1、学校…

BUG:AttributeError: module ‘websocket‘ has no attribute ‘enableTrace’

AttributeError: module ‘websocket’ has no attribute enableTrace’ 环境 windows 11 Python 3.10websocket 0.2.1 websocket-client 1.8.0 websockets 11.0.3 rel 0.4.9.19详情 一开始…

PromptCraft-Robotics部署步骤和问题记录

GitHub - microsoft/PromptCraft-Robotics: Community for applying LLMs to robotics and a robot simulator with ChatGPT integration 部署环境:UE4.27 Visual Studio 2022 Arisim1.8.1 可参考:git clone https://github.com/Microsoft/AirSim.gi…

保函到期提醒是银行或金融机构提供的一项服务,旨在确保客户及时了解保函即将到期的情况,从而避免因保函过期而导致的风险或违约责任。

保函到期提醒是银行或金融机构提供的一项服务,旨在确保客户及时了解保函即将到期的情况,从而避免因保函过期而导致的风险或违约责任。以下是保函到期提醒的一些关键方面: 1. **保函定义**: - 保函是一种由银行出具的书面承诺&…

CPU通过网络将IP camera的RTSP流(H.264编码或是H.265编码)拉回, 交给GPU解码并显示的处理流程

这个流程涉及到从IP摄像头获取视频流(通过RTSP协议),然后将流传输给GPU进行解码和显示的过程。详细的流程描述如下: 1. 获取视频流: - **IP摄像头**: 摄像头通过RTSP(Real-Time Streaming Protocol)将…

数据结构——树的基础概念

目录 1.树的概念 2.树的相关概念 3.树的表示 (1)直接表示法 (2)双亲表示法 (3)左孩子右兄弟表示法 4.树在实际中的运用(表示文件系统的目录树结构) 1.树的概念 树是一种非线性的数据结构&#xff0…

华为 RIP 协议中 RIP 兼容版本、RIPv1、RIPv2 在收发 RIP 报文时的区别

华为 RIP 协议中 RIP 兼容版本、RIPv1、RIPv2 的区别 为了更好地支持实际环境中路由器对 RIP 的支持,华为 VRP 平台具有一个兼容版本,默认情况下启动 RIP 进程后,如果没有配置 RIP 版本,该版本就为兼容版本,对 versio…

探索 SecureCRT:强大的终端 SSH 工具

SecureCRT 是一款功能强大、备受赞誉的终端 SSH 工具,适用于 Mac 和 Windows 操作系统,为用户提供了便捷、高效、安全的远程连接和管理体验。 SecureCRT 拥有直观友好的用户界面,即使是初次使用的用户也能迅速上手。其支持多种协议&#xff…