为什么 google oauth 流程在从前端启动时失败,但如果我直接从后端启动似乎有效?

Why google oauth flow is failing when initiated from frontend, but seems to work if I initiate from backend directly?

我有一个使用 flask-dance 的 Flash 后端,以允许 Web 应用程序使用 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。

为什么会这样?

我怀疑 运行 来自不同域的本地后端与它有关,但我不太清楚到底发生了什么以及如何解决这个问题。

您请求的 Google OAuth URL (https://accounts.google.com/o/oauth2/auth) 是他们身份验证过程的起点 - 它需要完整的浏览器 - 它需要显示凭据表单,同意然后将浏览器重定向回您的应用程序。这就是为什么您不能使用 XMLHttpRequest 访问它的原因。

您的后端 CORS 设置无济于事 - Google 必须在其端点上启用它,但由于前面提到的原因它仍然无法工作。