flaskoauthgoogle-oauthflask-oauthlib

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


I have an app written with Flask and try 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 in the 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 on button in the app I go to /auth/google and there (after redirects) I can see a google accounts list to choose from. When I select an account in the Network dev tools I see the following routing (url parameters missing):

  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= ...

all starts from the beginning and I see a "choose account" 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 set OAUTHLIB_INSECURE_TRANSPORT=1 and OAUTHLIB_RELAX_TOKEN_SCOPE=1

It seems like the third URL in routing should be /auth/google and try to resolve google.authorized once again but it does not and I see result of print(google.authorized) # False only once when click on a google button inside the app.


Solution

  • The blueprint generated by make_google_blueprint defaults to redirecting towards / when the authentication cycle has ended; you can configure this using the parameters redirect_url or redirect_to. In your case:

    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'
    )
    

    EDIT: Also make sure your app has a good secret_key set.