Integrating Google Authentication for a Flask App

Integrating Google Authentication for a Flask App

To add Google authentication as an option for sign up and sign in alongside the traditional username and email method in a Flask app, you'll need to integrate OAuth2 authentication using Google's APIs.

Below is a step-by-step guide to accomplish this:

Step 1: Set Up Google Developer Console

  1. Go to the Google Developers Console.

  2. Create a new project or select an existing one.

  3. Navigate to the "Credentials" tab.

  4. Click on "Create Credentials" and select "OAuth client ID".

  5. Choose "Web application" as the application type.

  6. Set the authorized redirect URIs. For local development, it might be http://localhost:5000/auth/google/callback. For production, it should be your actual domain.

  7. Note down the Client ID and Client Secret generated. You'll need these for configuration.

Step 2: Install Required Packages

Ensure you have Flask-OAuthlib and Flask-Login installed in your Flask project. You can install them using pip:

pip install Flask-OAuthlib Flask-Login

Step 3: Configure Flask App

In your Flask app's configuration, add the following:

# config.py

GOOGLE_CLIENT_ID = 'YOUR_GOOGLE_CLIENT_ID'
GOOGLE_CLIENT_SECRET = 'YOUR_GOOGLE_CLIENT_SECRET'

Step 4: Set Up OAuth Routes

Create routes to handle Google authentication:

# routes.py

from flask import Flask, redirect, url_for, session
from flask_oauthlib.client import OAuth

app = Flask(__name__)
app.secret_key = 'your_secret_key'
oauth = OAuth(app)

google = oauth.remote_app(
    'google',
    consumer_key=app.config.get('GOOGLE_CLIENT_ID'),
    consumer_secret=app.config.get('GOOGLE_CLIENT_SECRET'),
    request_token_params={
        'scope': 'email',
    },
    base_url='https://www.googleapis.com/oauth2/v1/',
    request_token_url=None,
    access_token_method='POST',
    access_token_url='https://accounts.google.com/o/oauth2/token',
    authorize_url='https://accounts.google.com/o/oauth2/auth',
)

@app.route('/login')
def login():
    return google.authorize(callback=url_for('authorized', _external=True))

@app.route('/logout')
def logout():
    session.pop('google_token', None)
    return redirect(url_for('index'))

@app.route('/login/authorized')
def authorized():
    resp = google.authorized_response()
    if resp is None or resp.get('access_token') is None:
        return 'Access denied: reason={}, error={}'.format(
            request.args['error_reason'],
            request.args['error_description']
        )

    session['google_token'] = (resp['access_token'], '')
    me = google.get('userinfo')
    return 'Logged in as: ' + me.data['email']

@google.tokengetter
def get_google_oauth_token():
    return session.get('google_token')

Step 5: Create Login Page

Create HTML templates for login and signup pages where users can choose between traditional login and Google authentication.

Step 6: Update User Authentication Logic

Modify your user authentication logic to handle both traditional login and Google authentication. You'll need to create users in your database upon successful Google authentication and link them with their Google accounts.

Step 7: Test

Test the authentication flow by signing up and signing in using both methods.

That's it! You've successfully integrated Google authentication alongside the traditional username and email login in your Flask app.