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

FastAPI+Authlib实现Google OAuth:Swagger正常HTML端失效

FastAPI与Authlib Google OAuth集成前端问题
  • 基于FastAPI官方安全教程及示例完成FastAPI与Authlib的Google OAuth集成,Swagger UI中功能正常:通过fastapi.security.OAuth2PasswordBearer表单登录Google账号后,可正常访问受保护路由。
  • HTML前端功能异常:点击包含<a href="/login">Google</a>的按钮,可跳转至/token端点并获取{"access_token": <my_token>, "token_type": "bearer"}格式的令牌,但无法自动跳转至受保护路由。
  • 尝试解决时,将XMLHttpRequest()绑定到按钮onclick事件,模拟GET请求访问/login,计划获取令牌后手动跳转,却触发CORS策略拦截,报错信息:

https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=<client_id>&redirect_uri=http%3A%2F%2F127.0.0.1%3A8004%2Fapi%2Fauth%2Fgoogle&scope=openid+email+profile&state=<state>' (redirected from 'http://127.0.0.1:8004/api/auth/login/google') from origin 'http://127.0.0.1:8004' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

  • 已尝试调整多种请求头、referrerPolicy配置及CORSMiddleware,仍无法用XMLHttpRequest()模拟<a>标签的跳转行为,不确定当前实现思路是否正确。
  • 最终需求:让该集成代码既能在Swagger中运行,也能在HTML前端正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 05:45:10