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

FastAPI中如何获取当前用户及传递fastapi_keycloak的idp对象至其他路由

FastAPI中fastapi_keycloak的两个核心问题解决方案

一、获取当前已认证用户

直接利用fastapi_keycloak提供的idp.get_current_user()作为Depends依赖项,在路由函数中声明OIDCUser类型的参数,即可自动获取当前完成认证的用户信息。

二、传递初始化后的idp对象给其他路由

不能在子路由文件中直接引用主文件的idp(会引发循环导入或未定义错误),推荐以下两种规范方案:

方案1:将idp封装到独立配置模块

创建keycloak_config.py文件,专门负责初始化和导出idp对象:

# keycloak_config.py
from fastapi_keycloak import FastAPIKeycloak

idp = FastAPIKeycloak(
    server_url="http://localhost:8085/auth",
    client_id="test-client",
    client_secret="GzgACcJzhzQ4j8kWhmhazt7WSdxDVUyE",
    admin_client_secret="BIcczGsZ6I8W5zf0rZg5qSexlloQLPKB",
    realm="Test",
    callback_uri="http://localhost:8081/callback"
)

随后在主文件和子路由文件中统一导入该idp:

# app.py
from fastapi import FastAPI
from keycloak_config import idp
import test_route

app = FastAPI()
idp.add_swagger_config(app)
app.include_router(test_route.test_router)
# test_route.py
from fastapi import APIRouter, Depends
from fastapi_keycloak import OIDCUser
from keycloak_config import idp

test_router = APIRouter()

@test_router.get("/current_user/roles", tags=["example-user-request"])
def get_current_users_roles(user: OIDCUser = Depends(idp.get_current_user())):
    return user.roles

方案2:通过依赖注入传递idp

若不想单独创建配置模块,也可通过自定义依赖项传递idp,但方案1的模块化方式更利于维护和避免配置重复。

关键注意点

  • OIDCUser内置了用户角色、ID、用户名等核心认证信息,直接通过路由参数声明即可获取。
  • 确保idp对象仅初始化一次,避免重复创建连接或配置冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 21:17:39