Login Google using Python Flask

Tram Ho

This article I will guide the most basic way to be able to login to Google Oauth2 in Flask web application with request-oauthlib package for OAuth 2.0 and jar-sqlalchemy.

To begin, we must first create a project in Google Developers to get the client key and client secret.

1. Create a Google project

First, visit the Google Developers Console. Sign in with your Google credentials if you don’t already have one. There will be a list of projects (if you have created them before with any of your projects).

Create a new project.

You enter the name you want to enter. Now go to the project page. Click API and Auth -> Authentication information in the left bar.

Then go to the OAuth consent screen. Provide Product Name (you may also provide other details but they are optional). Product names are what users see when they sign in to your application with Google.

Now click on the Authentication Information section. Then click on Add credentials and then select OAuth 2.0 customer ID.

Select Web Application Application Type, Provide authorized Javascript name and origin, and authorized redirect URI and click Create. During development, we will use localhost as our URL.

After the above step, you will see a dialog box with client ID and client secret. Copy both strings and save in a text file because we will need these strings.

2. Create the User table in Database

We will use flask-sqlalchemy to handle DB operations.

3. Create config for the application.

If we use flask-login to manage user sessions, we can check if the user is logged in. If not logged in, we redirect the user to the login page containing the link to the Google login. Create a config.py file to configure the relevant parameters of Google OAuth.

  • REDIRECT_URI is what we Google Developers Console for Google developers
  • AUTH_URI is where users are taken to sign in to Google
  • TOKEN_URI is used to exchange temporary tokens for access_token
  • USER_INFO is the URL used to retrieve user information such as name, email, etc. after successful authentication.
  • SCOPE is the type of user information that we will access after the user authenticates the application. Google OAuth2 Playground has a list of scopes that can be added.

URL routes for login and callback

requests_oauthlib.OAuth2Session helper

Root URL:

Callback URL:

Run serve.py to test.



Share the news now

Source : Viblo