Can anyone point me to a complete example for authenticating with Google accounts using OAuth2 and Flask, and not on App Engine?
I am trying to have users g
It looks like the new module Flask-Rauth is the answer to this question:
Flask-Rauth is a Flask extensions that allows you to easily interact with OAuth 2.0, OAuth 1.0a, and Ofly enabled applications. [...] This means that Flask-Rauth will allow users on your Flask website to sign in to external web services (i.e. the Twitter API, Facebook Graph API, GitHub, etc).
See: Flask-Rauth
I was able to port the accepted answer to use Requests-OAuthlib instead of Rauth. As of this writing, the package's last commit was on June 2019 and was currently use by 30K+ repositories.
To install, run:
$ pip install requests_oauthlib
Note, OAUTHLIB_RELAX_TOKEN_SCOPE
environment variable must be set to True
to suppress Scope has changed warning. On windows, this can be done by running:
$ set OAUTHLIB_RELAX_TOKEN_SCOPE=1
...
from requests_oauthlib import OAuth2Session
from urllib.request import urlopen
class GoogleSignIn(OAuthSignIn):
openid_url = "https://accounts.google.com/.well-known/openid-configuration"
def __init__(self):
super(GoogleLogin, self).__init__("google")
self.openid_config = json.load(urlopen(self.openid_url))
self.session = OAuth2Session(
client_id=self.consumer_id,
redirect_uri=self.get_callback_url(),
scope=self.openid_config["scopes_supported"]
)
def authorize(self):
auth_url, _ = self.session.authorization_url(
self.openid_config["authorization_endpoint"])
return redirect(auth_url)
def callback(self):
if "code" not in request.args:
return None, None
self.session.fetch_token(
token_url=self.openid_config["token_endpoint"],
code=request.args["code"],
client_secret=self.consumer_secret,
)
me = self.session.get(self.openid_config["userinfo_endpoint"]).json()
return me["name"], me["email"]
Requests-OAuthlib documentation can be found here https://requests-oauthlib.readthedocs.io/en/latest/index.html.
As oauth2client is now deprecated, I recommend what bluemoon suggests. Bruno Rocha's model of OAuth2 Google authentication in Flask is a nice starting point for using lepture's robust Flask-OAuthlib (pip-installable). I recommend mimicking, then expanding to suit your needs.