FastAPI - 安全(Security)4

删除routers/member.py文件

修改main.py文件

复制代码
# -*- coding:utf-8 --*-
from fastapi import Depends,FastAPI

from fastapi.security import OAuth2PasswordBearer
from typing import Annotated

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

app = FastAPI(
    title="文档标题",
    description="关于API文档的补充说明",
    version="1.0.0",
    docs_url="/docs"
)


@app.get("/items/")
async def read_items(token: Annotated[str, Depends(oauth2_scheme)]):
    return {"token": token}

https://fastapi.tiangolo.com/zh/tutorial/security/first-steps

创建用户模型

修改main.py文件

复制代码
# -*- coding:utf-8 --*-
from fastapi import Depends, FastAPI

from fastapi.security import OAuth2PasswordBearer
from typing import Annotated
from pydantic import BaseModel

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")


class User(BaseModel):
    username: str
    email: str | None = None
    full_name: str | None = None
    disabled: bool | None = None


def fake_decode_token(token):
    return User(
        username=token + "fakedecoded", email="vvv@example.com", full_name="vvv lao"
    )


async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
    user = fake_decode_token(token)
    return user

app = FastAPI(
    title="文档标题",
    description="关于API文档的补充说明",
    version="1.0.0",
    docs_url="/docs"
)


@app.get("/users/me")
async def read_users_me(current_user: Annotated[User, Depends(get_current_user)]):
    return current_user

其中get_current_user使用oauth2_scheme作为依赖项

https://fastapi.tiangolo.com/zh/tutorial/security/simple-oauth2

相关推荐
俊俊谢20 小时前
[python]FastAPI + 自建SSE 踩坑全记录
开发语言·python·fastapi
li星野1 天前
从零搭建 DeepSeek LLM API 服务:FastAPI + LlamaIndex 实践
fastapi
勇往直前plus1 天前
FastAPI + SQLAlchemy PythonWeb体系梳理
fastapi·python3.11
放下华子我只抽RuiKe52 天前
FastAPI 全栈后端(四):认证与授权
开发语言·前端·javascript·python·深度学习·react.js·fastapi
放下华子我只抽RuiKe52 天前
FastAPI 全栈后端(六):中间件与依赖注入
ai·中间件·fastapi·ai编程·qwen·ai大模型·openclaw
li星野2 天前
Refresh Token 实战:让用户“无感”续期,告别重复登录
fastapi
放下华子我只抽RuiKe52 天前
FastAPI 全栈后端(五):后台任务与消息队列
前端·javascript·react.js·ai·前端框架·fastapi·ai编程
li星野3 天前
从零构建安全文件上传系统:FastAPI + JWT + 密码哈希 + Streamlit 前端 + SQLite
安全·哈希算法·fastapi
郭庆汝4 天前
FastAPI使用笔记
笔记·fastapi
放下华子我只抽RuiKe54 天前
FastAPI 全栈后端(二):路由与数据模型
前端·人工智能·react.js·前端框架·html·fastapi