# Google Authentication in Python and Flask
Source: https://docs.replit.com/additional-resources/google-auth-in-flask
Learn how to implement Google OAuth authentication in a Flask app on Replit, including user login and Google Sheets API integration.
Allowing your users to log in to your website using their Google account has these benefits:
1. You don't have to implement your own authentication scheme.
2. You can get users' name and contact information easily.
3. You can use the same credentials to access users' Google resources like Sheets and Drive.
This guide that will walk you through how to do that with Python and Flask on Replit.
First, we'll walk through how to setup basic OAuth authentication, then cover how to use the resulting credentials to access users' Google resources.
## Introduction to OAuth
Google authentication is based on the OAuth standard. The way OAuth works is as follows:
1. Somewhere on your website, you direct a user to a login page.
2. When they go to the login page, you don't implement the login form on your website, but instead redirect to Google's login service to login the user.
3. When Google's login service successfully logs in the user, it redirects back to your website at a predefined URL of your choosing, say `https://YOUR_DOMAIN/oauth2callback`, while sending some information pertinent to the user and the login session.
4. You use the user's login information to further obtain an access token, which is like a pass you can use to access the user's resources, like their profile information, their spreadsheets, documents and more.
## OAuth: Show me the code
If you are like me, the first thing you want is working code. The code below is what you need. However, you'll need to set up some things in your Google Cloud Console in order to get everything working. That will be covered in the next section. Create a new Replit App using the [Flask template](https://replit.com/@replit/Flask?v=1) and put the following in `main.py`. The comments in the code explains what the individual parts do:
```python theme={null}
from flask import Flask, redirect, session, url_for, request
import google_auth_oauthlib.flow
import json
import os
import requests
app = Flask('app')
# `FLASK_SECRET_KEY` is used by sessions. You should create a random string
# and store it as secret.
app.secret_key = os.environ.get('FLASK_SECRET_KEY') or os.urandom(24)
# `GOOGLE_APIS_OAUTH_SECRET` contains the contents of a JSON file to be downloaded
# from the Google Cloud Credentials panel. See next section.
oauth_config = json.loads(os.environ['GOOGLE_OAUTH_SECRETS'])
# This sets up a configuration for the OAuth flow
oauth_flow = google_auth_oauthlib.flow.Flow.from_client_config(
oauth_config,
# scopes define what APIs you want to access on behave of the user once authenticated
scopes=[
"https://www.googleapis.com/auth/userinfo.email",
"openid",
"https://www.googleapis.com/auth/userinfo.profile",
]
)
# This is entrypoint of the login page. It will redirect to the Google login service located at the
# `authorization_url`. The `redirect_uri` is actually the URI which the Google login service will use to
# redirect back to this app.
@app.route('/signin')
def signin():
# We rewrite the URL from http to https because inside the Replit App http is used,
# but externally it's accessed via https, and the redirect_uri has to match that
oauth_flow.redirect_uri = url_for('oauth2callback', _external=True).replace('http://', 'https://')
authorization_url, state = oauth_flow.authorization_url()
session['state'] = state
return redirect(authorization_url)
# This is the endpoint that Google login service redirects back to. It must be added to the "Authorized redirect URIs"
# in the API credentials panel within Google Cloud. It will call a Google endpoint to request
# an access token and store it in the user session. After this, the access token can be used to access
# APIs on behalf of the user.
@app.route('/oauth2callback')
def oauth2callback():
if not session['state'] == request.args['state']:
return 'Invalid state parameter', 400
oauth_flow.fetch_token(authorization_response=request.url.replace('http:', 'https:'))
session['access_token'] = oauth_flow.credentials.token
return redirect("/")
# This is the home page of the app. It directs the user to log in if they are not already.
# It shows the user info's information if they already are.
@app.route('/')
def welcome():
if "access_token" in session:
user_info = get_user_info(session["access_token"])
if user_info:
return f"""
Hello {user_info["given_name"]}!
Your email address is {user_info["email"]}
Log out
"""
return """
Explore visual variations and apply a new design without rebuilding.
Run multiple Agent tasks at once so different parts of the app move forward together.
Learn how to guide Agent from idea to working app.
Save app data after refresh.