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):
https://accounts.google.com/_/signin/oauth?authuser=
http://127.0.0.1:8001/google_login/google/authorized?state=
http://127.0.0.1:8001/google_login/google
And then:
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.
redirect_url
andredirect_to
. Now I wroteredirect_to='auth.google'
and get a werkzeug error, so it has been handled. Then I correct it toauth.auth_google_view
and still has the same issue with routing: /auth/google -> /google_login/google -> (choose account) -> /google_login/google -> (choose account) ... And still seeprint(google.authorized)
only once on button click. How it's possible? – Scriptorium