Integrate Google Authentication in your Flask apps Easily

Integrate Google Authentication in your Flask apps Easily

Authlib Google OAuth 2.0 Setup for Flask apps

Play this article

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

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

Install authlib for the integration

pip install authlib

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)

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

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

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

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

Did you find this article valuable?

Support RF Coding Chronicles by becoming a sponsor. Any amount is appreciated!