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
相关产品推荐
相关产品推荐

