Google OAuth with Flask-Dance (always redirect to google select account page)

I have an application written in Flask and I am trying to use Flask-Dance ( Flask-Dance Docs - Google Example ) to enable Google OAuth. I got the following setup:

from flask import redirect, url_for, jsonify, Blueprint
from flask_dance.contrib.google import make_google_blueprint, google

from server.app import app

# Internal auth blueprint
auth = Blueprint('auth', __name__, url_prefix='/auth')

# Google auth blueprint
google_login = make_google_blueprint(
    client_id=app.config['GOOGLE_CLIENT_ID'],
    client_secret=app.config['GOOGLE_CLIENT_SECRET'],
    scope=['profile', 'email']
)


def auth_google_view():
    """
    Authenticate user with google
    """

    # Not authorized
    print(google.authorized)
    if not google.authorized:
        return redirect(url_for('google.login'))

    # Authorized - check data
    user_info = google.get('/oauth2/v2/userinfo')
    if user_info.ok:
        return jsonify({'status': 'ok', 'email': user_info.json() .['email']}), 200
    return jsonify({'status': 'failed'})


# Add urls
auth.add_url_rule('/google', view_func=auth_google_view)

And then at app/__init__.py:

from server.app.auth import auth, google_login

app.register_blueprint(auth)
app.register_blueprint(google_login, url_prefix='/google_login')

By clicking the button in the application, I go to /auth/googleand there (after redirecting) I see a list of Google accounts to choose from. When I select an account in Network dev tools, I see the following routing (no URL parameters):

  1. https://accounts.google.com/_/signin/oauth?authuser=
  2. http://127.0.0.1:8001/google_login/google/authorized?state=
  3. http://127.0.0.1:8001/google_login/google

And then:

  1. https://accounts.google.com/o/oauth2/auth?response_type= ...

it all starts from the very beginning, and I see the account selection screen.

In the Google API account, I have a redirect URL:

http://127.0.0.1:8001/google_login/google/authorized

In the development environment, I installed OAUTHLIB_INSECURE_TRANSPORT=1andOAUTHLIB_RELAX_TOKEN_SCOPE=1

, URL- /auth/google google.authorized , , print(google.authorized) # False , Google .

+7
1

, make_google_blueprint , /; redirect_url redirect_to. :

google_login = make_google_blueprint(
  client_id=app.config['GOOGLE_CLIENT_ID'],
  client_secret=app.config['GOOGLE_CLIENT_SECRET'],
  scope=['profile', 'email'],
  redirect_to='auth.auth_google_view'
)

. , secret_key.

+5

Source: https://habr.com/ru/post/1696010/


All Articles