Integrate Google Authentication in Flask Apps Quickly and Easily
Tags: flask, webdev, tips, oauth
Published: 2022-12-05 13:16:33

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

```python
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

```python
pip install authlib
```

For more info visit docs: [https://docs.authlib.org/en/latest/client/flask.html](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](https://console.cloud.google.com/apis/credentials) and go to this page

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e79zn6nxwbks8gfpcyuj.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vv7f360ajew638ojyhv8.png)

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](http://localhost:8000/authorize)

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

## Initialize auth app

```python
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

```python
#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

```python
#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

```python
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.

Follow me on hashnode : [Hashnode Blog](https://fahadislam.hashnode.dev)