DEV Community

Cover image for Integrate Google Authentication in Flask Apps Quickly and Easily
RF Fahad Islam
RF Fahad Islam

Posted on • Updated on

Integrate Google Authentication in Flask Apps Quickly and Easily

Let's see how to make a google login system for our flask apps in only 2 minutes.

First, Look at the simple app of Flask



from flask import Flask,render_template
app = Flask(__name__)
@app.route('/')
def home():
    return render_template('index.html')
if __name__ == "__main__":
    app.run()


Enter fullscreen mode Exit fullscreen mode

This is our simple flask app. Now let's add google auth.

Install authlib for the integration



pip install authlib


Enter fullscreen mode Exit fullscreen mode

For more info visit docs: https://docs.authlib.org/en/latest/client/flask.html

Get Google Auth API Keys

Go to the credentials page and sign in: https://console.cloud.google.com/apis/credentials and go to this page

Image description

Then select OAuth Client Id and then select web application in the form.

Image description

Fill in the name of the app and then provide authorized redirect URLs. In this tutorial, the authorized link will be: http://localhost:8000/authorize

Finally, create and copy the google client id and client secret

Initialize auth app



from authlib.integrations.flask_client import OAuth
#Authlib
oauth = OAuth(app)


Enter fullscreen mode Exit fullscreen mode

Then create the google client and configure Provide your google client id and secret here



#Register google outh
google = oauth.register(
  name='google',
  server_metadata_url=CONF_URL,
  # Collect client_id and client secret from google auth api
  client_id= "GOOGLE_CLIENT_ID",
  client_secret = "GOOGLE_CLIENT_SECRET",
  client_kwargs={
    'scope': 'openid email profile'
  }
)


Enter fullscreen mode Exit fullscreen mode

Routes for google login page

Here are the routes for the google login page



#Routes for login
@app.route('/google-login')
def googleLogin():
    # Here is the authorized url page
    redirect_uri = url_for('authorize', _external=True)
    google = oauth.create_client('google')
    #then return the user to authorized login page of google
    return google.authorize_redirect(redirect_uri)


@app.route('/authorize')
def authorize():
    """Google login page will apear in this will provide you with 
    information of user"""
    token = oauth.google.authorize_access_token()
    user = token['userinfo'] # This is the dict for userinfo
    #user will return a dict of info like: email = user.get("email")
    #Save the user info to database and login the user


Enter fullscreen mode Exit fullscreen mode

Final Code



from authlib.integrations.flask_client import OAuth
from flask import Flask, render_template

# More Info : https://docs.authlib.org/en/latest/client/flask.html
app = Flask(__name__)
#Authlib
oauth = OAuth(app)

#Register google outh

CONF_URL = 'https://accounts.google.com/.well-known/openid-configuration' #provide us with common metadata configurations 
google = oauth.register(
  name='google',
  server_metadata_url=CONF_URL,
  # Collect client_id and client secret from google auth api
  client_id= os.environ.get("GOOGLE_CLIENT_ID"),
  client_secret = os.environ.get("GOOGLE_CLIENT_SECRET"),
  client_kwargs={
    'scope': 'openid email profile'
  }
)

#Routes for login
@app.route('/google-login')
def googleLogin():
    redirect_uri = url_for('authorize', _external=True)
    google = oauth.create_client('google')
    return google.authorize_redirect(redirect_uri)


@app.route('/authorize')
def authorize():
    token = oauth.google.authorize_access_token()
    user = token['userinfo']
  # user will return a dict of info like: email = user.get("email")
    #Save the user info to database and login the user


Enter fullscreen mode Exit fullscreen mode

Congrats🎉🎉. Now you have google authentication in your flask app🥳 Happy Coding.

Follow me on hashnode : Hashnode Blog

Top comments (0)