admin管理员组

文章数量:1289868

I'm building a web app using Flask with Google OAuth for calendar integration. I’m running into an issue where a new session is created after the user is redirected back from Google’s OAuth login. This results in losing the stored google_credentials, causing authentication failures when attempting to add events to Google Calendar.

  • Issue: After a successful login, the user is redirected to the “Add Events to Calendar” page, but a new session is created, and the google_credentials are lost.
  • Expected Behavior: The session should persist across the OAuth redirect, retaining the google_credentials.
  • Actual Behavior: A new session file is created in the flask_session folder, and session.keys() shows only ['_permanent'].

What I've tried:

  1. Session Configuration
`app.config["SESSION_TYPE"] = "filesystem"
    app.config["SESSION_PERMANENT"] = False
    app.config["SESSION_USE_SIGNER"] = True
    app.config["SESSION_FILE_DIR"] = "./flask_session"
    app.config["SESSION_COOKIE_SAMESITE"] = "None"
    app.config["SESSION_COOKIE_SECURE"] = True
    Session(app)`

  1. Debugging Steps: Verified that cookies are being set in the browser. Confirmed that session data (google_credentials) is stored before redirect. Observed that a new session file is created in flask_session after the redirect.

  2. Attempted Solutions: Setting SESSION_COOKIE_SAMESITE to "None" and SESSION_COOKIE_SECURE to True. Manually printing session.keys() to verify session state.

Relevant Code:

 `@app.route("/google/callback")
 def google_callback():
    code = request.args.get("code")
    if not code:
        return jsonify({"error": "Authorization code not received."}), 400

     token_url = ";
     data = {
         "client_id": GOOGLE_CLIENT_ID,
        "client_secret": GOOGLE_CLIENT_SECRET,
        "code": code,
        "grant_type": "authorization_code",
        "redirect_uri": REDIRECT_URI,
    }

    response = requests.post(token_url, data=data)
    tokens = response.json()

     if "access_token" in tokens:
        credentials = Credentials(
            tokens["access_token"],
            refresh_token=tokens.get("refresh_token"),
            token_uri=";,
            client_id=GOOGLE_CLIENT_ID,
            client_secret=GOOGLE_CLIENT_SECRET,
         )
        session["google_credentials"] = credentials.to_json()
        session.modified = True

      print(f"[DEBUG] Google credentials stored {session['google_credentials']}")
         return redirect("http://localhost:3000")
    else:
         return jsonify({"error": "Failed to retrieve access token."}), 400`

本文标签: Flask Google OAuth Creates New Session After RedirectHow to Persist Session DataStack Overflow