FastAPI对接Keycloak如何实现Swagger UI的Refresh Token自动刷新
Swagger自动续期Bearer令牌实现方案
1. 配置OpenAPI规范的刷新令牌支持
FastAPI默认的OAuth2PasswordBearer配置生成的OpenAPI文档仅声明了密码登录的令牌获取端点,缺少刷新端点的配置,Swagger UI的内置OAuth客户端无法触发自动刷新逻辑。需要手动覆写OpenAPI生成逻辑,补充刷新端点声明:
from fastapi import FastAPI from fastapi.openapi.utils import get_openapi from fastapi.security import OAuth2PasswordBearer from jose import jwt import time import requests import json app = FastAPI() # 原有依赖注入用的oauth2_scheme保留 oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token") def custom_openapi(): if app.openapi_schema: return app.openapi_schema openapi_schema = get_openapi( title="组织内部API服务", version="1.0.0", routes=app.routes, ) # 给OAuth2安全配置补充刷新端点声明 security_scheme = openapi_schema["components"]["securitySchemes"]["OAuth2PasswordBearer"] security_scheme["refreshUrl"] = "/refresh" security_scheme["x-usePkce"] = False app.openapi_schema = openapi_schema return app.openapi_schema app.openapi = custom_openapi
配置说明:Swagger UI内置OAuth客户端检测到securityScheme包含
refreshUrl字段后,会在收到请求401响应时自动调用该端点完成令牌刷新,无需额外前端逻辑。
2. 实现符合规范的令牌刷新接口
复用现有缓存的refresh_token,对接Keycloak的刷新令牌流程,提供标准化的刷新接口:
@app.post("/refresh") async def refresh_token(refresh_token: str = Body(..., embed=True)): # 从本地缓存匹配对应refresh_token的用户记录 matched_user = None matched_record = None for username, record in TOKEN_CACHE.items(): if record.get("refresh_token") == refresh_token: matched_user = username matched_record = record break if not matched_record: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid refresh token", headers={"WWW-Authenticate": "Bearer"}, ) # 调用Keycloak接口换取新的访问令牌 keycloak_refresh_resp = requests.post( "https://mygreatorg.com/auth/realms/master/protocol/openid-connect/token", data={ "grant_type": "refresh_token", "client_id": "fastapi-application", "refresh_token": refresh_token, } ) new_token_info = json.loads(keycloak_refresh_resp.content.decode("utf-8")) new_token_info["acquire_time"] = time.time() # 更新本地缓存的令牌信息 TOKEN_CACHE[matched_user] = new_token_info # 返回Swagger可识别的标准响应格式 return { "access_token": new_token_info["access_token"], "refresh_token": new_token_info["refresh_token"], "token_type": "bearer", "expires_in": new_token_info["expires_in"] }
3. 原有登录逻辑的适配调整
原有的/token登录接口仅返回访问令牌,缺少Swagger刷新所需的refresh_token字段,需要调整返回值:
@app.post("/token") async def login(form_data: OAuth2PasswordRequestForm = Depends()): login_request = requests.post( "https://mygreatorg.com/auth/realms/master/protocol/openid-connect/token", data={ "grant_type": "password", "username": form_data.username, "password": form_data.password, "client_id": "fastapi-application", }, ) raw_response = json.loads(login_request.content.decode('utf-8')) raw_response['acquire_time'] = time.time() TOKEN_CACHE[form_data.username] = raw_response # 补充返回refresh_token字段,供Swagger存储用于自动刷新 return { "access_token": raw_response['access_token'], "refresh_token": raw_response['refresh_token'], "token_type": "bearer", "expires_in": raw_response['expires_in'] }
关键注意事项
- 原有的JWT解码、过期检测逻辑完全保留,严格执行1分钟短有效期的安全要求,不会降低安全等级
- 当refresh_token也过期时,Keycloak会返回401错误,此时才需要用户重新输入账号密码登录,完全符合OAuth2的安全设计
- Swagger自动刷新的触发逻辑为内置能力:只要收到携带
WWW-Authenticate: Bearer头的401响应,就会自动调用配置的refreshUrl,无需用户手动操作
内容的提问来源于stack exchange,提问作者hirolau
相关产品推荐
相关产品推荐

