我有一个使用 flask-dance 的 Flash 后端,以允许网络应用程序通过 Google 提供商对用户进行身份验证。
在我的本地开发环境中,后端从 运行https://localhost:5000
,而我的本地前端在https://local.mydomain.com
我有一个后端端点https://localhost:5000/login/google
,将用户重定向到 Google OAuth 流:
@app.route('/login/<provider>')
def login(provider: str):
# here we store the page the user has come from with the referrer value
session["return_to"] = request.referrer
if provider == 'google':
return redirect(url_for("google.login"))
return False
如果我直接在浏览器中访问此 URL,我将被重定向到 Google,并且 OAuth 流程成功完成。
但是,如果我在前端添加一个重定向到该 URL 的按钮,OAuth 流程会在中途失败,并且浏览器会打印以下错误:
Access to XMLHttpRequest at 'https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=580945975384-0mqduo9k8dchc0ho7tnd7g6ejo70jrlb.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Flocalhost%3A5000%2Fauth%2Fgoogle%2Fauthorized&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+openid&state=tWt5b2pkp0jfjxtXD8aHlMwsKyuCJw' (redirected from 'https://localhost:5000/login/google') from origin 'https://local.mydomain.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
index.js:1 Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:117)
xhr.js:210 GET https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=580945975384-0mqduo9k8dchc0ho7tnd7g6ejo70jrlb.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Flocalhost%3A5000%2Fauth%2Fgoogle%2Fauthorized&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+openid&state=tWt5b2pkp0jfjxtXD8aHlMwsKyuCJw net::ERR_FAILED 200
这是失败的请求:
Flask 后端应用启用了 CORS。
为什么会这样?
我怀疑从不同域本地运行后端与它有关,但我无法完全弄清楚发生了什么以及如何解决这个问题。