React fetch to flask route that handles google auth gives CORS error

问题描述 投票:0回答:0

我通过 OAuth 在 Flask 中设置了 Google 身份验证。我已经检查过它是否可以手动工作。

我的应用程序在前端使用 React,所以我创建了一个登录按钮来点击 flask 中的登录路径。 这是运行该路由的 React 获取请求。

  function handleLogin() {
    fetch('/login')
      .then(response => response.json())
      .then(response => {
        console.log(response)
      })
      .catch(error => {
        // Handle error
      });
  }

这是我的烧瓶路线,当我访问烧瓶运行位置上的 /login 路线时,这些路线已被证明有效。

@app.route('/login')
def login():
    google = oauth.create_client('google')
    redirect_uri = url_for('authorize', _external=True)
    return google.authorize_redirect(redirect_uri)

@app.route('/auth')
def authorize():
    google = oauth.create_client('google')
    token = google.authorize_access_token()
    resp = google.get('userinfo').json()
    # Check if the user already exists in the database
    user = User.query.filter_by(email=resp['email']).first()
    # If the user doesn't exist, create a new user
    if not user:
        user = User(email=resp['email'], google_id=resp['id'])
        db.session.add(user)
        db.session.commit()
    # Log the user in using Flask-Login
    login_user(user)

    print(f"\n{resp}\n")
    return redirect(url_for('list_all'))

当我点击运行

handleLogin
的 React 按钮时收到的错误是 CORS 错误。

Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. Status code: 200
Fetch API cannot load <url for google's sign on>
Failed to load resource: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. Status code: 200

我尝试返回在

/login
路由中重定向的 URL,然后让 React 代码自行执行重定向。但这导致
raise MismatchingStateError() authlib.integrations.base_client.errors.MismatchingStateError: mismatching_state: CSRF Warning! State not equal in request and response.

@app.route('/login')
def login():
   ...
   authorization_url = google.authorize_redirect(redirect_uri)
   redirect_url = authorization_url.location
   return {"status" : 200, "url" : redirect_url}
fetch('/login')
      .then(response => response.json())
      .then(response => {
        // Redirect to authorization page
        console.log(response.url)
        window.location.href = response.url;
      })
      .catch(error => {
        // Handle error
      });
reactjs flask oauth google-oauth flask-login
© www.soinside.com 2019 - 2024. All rights reserved.