Skip to content

Instantly share code, notes, and snippets.

@leeyspaul
Created November 30, 2021 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leeyspaul/2c7bd03e4d1e0ba7e87995c32ee659f4 to your computer and use it in GitHub Desktop.
Save leeyspaul/2c7bd03e4d1e0ba7e87995c32ee659f4 to your computer and use it in GitHub Desktop.
OAuth2 Authorize Route for Google Calendar API
import flask
import google.oauth2.credentials
import google_auth_oauthlib.flow
import os
from flask import Flask
from flask import redirect
from flask import request
from googleapiclient.discovery import build
# set up a Flow object that reads the clients from our secrets file with the
# corresponding scope
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
'client_secrets.json',
scopes=['https://www.googleapis.com/auth/calendar'])
# indicate the redirect URI that we placed in the console redirect URI when we
# created the oauth credentials
flow.redirect_uri = 'http://localhost:8080/oauth2redirect'
# generates the auth URL that we need to redirect users to where the user
# gets the oauth consent screen and we get the access code to later exchange for an
# auth token
authorization_url, _ = flow.authorization_url(
# enables us to grab a refresh token without the user granting us access
# a second time if needed
access_type='offline',
include_granted_scopes='true')
# create our Flask web app
app = Flask(__name__)
# this allows transport over HTTP for development purposes, if excluded
# HTTPS is needed
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
@app.route("/authorize-user")
def auth_user():
"""
Redirects a user to Google's authorization server to show the OAuth
Consent screen and get user consent.
"""
return redirect(authorization_url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment