Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Error in redirection in Google OAuth2.0.

I'm encountering a "403 Forbidden" error in chrome when trying to implement Google OAuth 2.0 in my Flask application, in the terminal I get "127.0.0.1 - - [26/Nov/2024 23:50:16] "GET /login-google HTTP/1.1" 302 -" . Here's a detailed description of the issue:

  • Error: After attempting to log in with Google, I'm redirected to my callback URL, but I receive a "403 Forbidden" error.
  • Expected Behavior: The callback function should exchange the authorization code for an access token and retrieve user information.
  • Current Behavior: The redirection to the callback URL occurs, but the server responds with a 403 error, indicating a lack of authorization.

I have already:

  • the callback url is correctly configured.
  • Ensured that the OAuth consent screen is set up and my email is added as a test user.
  • Checked for correct client ID and secret in environment variables.
  • Tested in incognito mode to rule out browser extensions or cache issues.
My code implementation of oauth2.0:
  • Using authlib to handle the OAuth flow.
  • The login function redirects to Google's authorization endpoint.
  • The callback function is supposed to handle the token exchange.
 the environment I am using is a local development on Flask with authlib The server logs indicate that the callback function is not being reached, suggesting a possible issue with the redirection or session state.
I'm looking for guidance on resolving this 403 error. Any insights into potential misconfigurations or overlooked details in the OAuth setup would be greatly appreciated.
this is my code:
from flask import Blueprint, redirect, url_for, session, request
from requests_oauthlib import OAuth2Session
import os
import secrets
from dotenv import load_dotenv
from encrypt_decrypt_db import encrypt, decrypt

load_dotenv('xxx')

# ruta del directorio actual
current_dir = os.path.dirname(os.path.abspath(__file__))
# ruta a oauth.env
dotenv_path = os.path.join(current_dir, 'OAuth.env')
# variables de OAuth.env
load_dotenv(dotenv_path)

auth_bp = Blueprint('auth', __name__)

# OAuth config
client_id = xxx
client_secret = xxx
#print(f"Loaded Client ID: {client_id}")
#print(f"Loaded Client Secret: {client_secret}")

scope = [
"openid",
]

@auth_bp.route('/login-google')
def login_google():
google = OAuth2Session(client_id, scope=scope, redirect_uri=redirect_uri)
state = secrets.token_urlsafe(16)
authorization_url, _ = google.authorization_url(
authorization_base_url,
access_type="offline",
prompt="select_account",
state=state
)
session['oauth_state'] = state
return redirect(authorization_url)

@auth_bp.route('/callback')
def callback():
print ("hol1")
if request.args.get('state') != session['oauth_state']: # verify
print("hol2")
return "Error: Status does not match", 403

try:
print("hol3")
google = OAuth2Session(client_id, redirect_uri=redirect_uri, state=session['oauth_state'])
token = google.fetch_token(token_url, client_secret=client_secret, authorization_response=request.url)
 
session['oauth_token'] = encrypt(token['access_token'], k)

google = OAuth2Session(client_id, token=token)
user_info = google.get('https://www.googleapis.com/oauth2/v1/userinfo').json()
google_id = user_info.get('sub')

session['encrypted_user_info'] = {
'username': user_info.get('email', '').split('@')[0],
'email': encrypt(user_info.get('email', ''), k),
'name': encrypt(user_info.get('given_name', ''), k),
'surname': encrypt(user_info.get('family_name', ''), k),
'google_id': encrypt(google_id, k), # Encriptar el Google ID
}

except Exception as e:
print("hol1")
return "Error retrieving token or user information", 500

return redirect(url_for('register', session))
 
 
0 1 813
1 REPLY 1

Hi @margacm,

Welcome to Google Cloud Community! 

In addition to what you've already checked, it's worth verifying the session state. The state parameter is there to prevent cross-site request forgery (CSRF), so double-check that it's being set properly in your login_google function and correctly validated in the callback function. Adding some print statements or logging can help confirm whether the callback function is being triggered at all. If it isn’t, the problem might lie with the redirect URL or how the authorization code is being handled.

Taking a look at this document on general best practices for integrating with OAuth 2.0 could be a great way to refine your implementation and improve your code. It might provide some helpful insights or techniques you haven’t considered yet.

If you’re still stuck after troubleshooting, it might be a good idea to reach out to Google Cloud Support for additional guidance. Our support team is available to diagnose underlying issues. When you contact them, be sure to provide as much detail as possible and include screenshots. This will help them understand your problem better and get it sorted out more quickly.

Hope this helps!