You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何重写FastAPI内置Logout函数以清除Cookie中的Token?

FastAPI Swagger内置Logout按钮清除Cookie Token方案

可行性说明

完全可以重写Swagger Docs的内置Logout行为,让它调用你的自定义/logout接口来清除Cookie中的Token。FastAPI支持通过配置Swagger UI的初始化参数,或者自定义Swagger页面的方式,修改Logout按钮的默认逻辑。

具体实现方案

方案一:通过Swagger UI初始化配置修改Logout行为

直接在FastAPI实例初始化时,指定swagger_ui_init_oauth参数,将Logout请求指向你的自定义接口:

from fastapi import FastAPI
from app.routers import auth_router  # 导入你的认证路由

app = FastAPI(
    title="你的应用名称",
    docs_url="/docs",
    # 配置Swagger UI的OAuth参数,重点指定logoutUrl
    swagger_ui_init_oauth={
        "logoutUrl": "/logout",  # 指向你的自定义登出接口
        "clientId": "",  # 若无需OAuth客户端ID可留空
        "usePkceWithAuthorizationCodeGrant": True
    }
)

app.include_router(auth_router)

方案二:自定义Swagger UI页面(更灵活)

如果需要更精细的控制,比如添加登出后的页面刷新逻辑,可以覆盖默认的Swagger Docs路由,返回自定义的HTML:

from fastapi import FastAPI, Request
from fastapi.openapi.docs import get_swagger_ui_html
from app.routers import auth_router

# 先关闭默认的docs路由
app = FastAPI(docs_url=None, title="你的应用名称")

@app.get("/docs", include_in_schema=False)
async def custom_swagger_docs(request: Request):
    swagger_html = get_swagger_ui_html(
        openapi_url=app.openapi_url,
        title=f"{app.title} - Swagger UI",
        oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
        swagger_js_url="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js",
        swagger_css_url="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css",
        # 初始化OAuth配置
        swagger_ui_init_oauth={
            "logoutUrl": "/logout",
            "clientId": ""
        }
    )
    # 添加自定义脚本,确保登出后刷新页面并清除Swagger本地存储
    custom_script = """
    <script>
        window.addEventListener('load', function() {
            const logoutBtn = document.querySelector('.swagger-ui .topbar .auth-wrapper .logout-button');
            if (logoutBtn) {
                logoutBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    fetch('/logout', { method: 'POST' })
                        .then(() => {
                            localStorage.removeItem('swaggerToken');
                            window.location.href = '/docs';
                        });
                });
            }
        });
    </script>
    """
    # 将自定义脚本插入到Swagger HTML中
    return swagger_html.replace('</body>', f'{custom_script}</body>')

app.include_router(auth_router)

自定义Logout接口无需修改

你现有的/logout接口已经可以正确清除Cookie,保持原样即可:

@auth_router.post("/logout")
async def logout():
    response = RedirectResponse(url="/docs")
    response.delete_cookie(settings.COOKIE_NAME)
    return response

效果验证

配置完成后,点击Swagger Docs中的Logout按钮,会自动调用你的/logout接口,清除Cookie中的Token,同时重定向回Docs页面,此时再调用需要认证的接口会返回401未授权,符合预期。

内容的提问来源于stack exchange,提问作者Lyu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 08:03:25