Skip to content

Instantly share code, notes, and snippets.

@jetnew
Created August 16, 2023 04:53
Show Gist options
  • Save jetnew/075c4fae84832841a9772aeebe0234a4 to your computer and use it in GitHub Desktop.
Save jetnew/075c4fae84832841a9772aeebe0234a4 to your computer and use it in GitHub Desktop.
Minimal Flask server for Google API credentials OAuth2 authentication.
import os
from flask import Flask, session, abort, redirect, request
from google_auth_oauthlib.flow import Flow
app = Flask(__name__)
app.secret_key = os.urandom(24)
# Get client secrets file from https://console.cloud.google.com/apis/credentials -> OAuth client ID -> Web application
flow = Flow.from_client_secrets_file(
client_secrets_file="<client-secrets>.json",
scopes=["https://mail.google.com/"],
redirect_uri="https://<auth-server-url>/callback"
)
@app.route("/")
def login():
authorization_url, state = flow.authorization_url()
session["state"] = state
return redirect(authorization_url)
@app.route("/callback")
def callback():
flow.fetch_token(authorization_response=request.url)
if not session["state"] == request.args["state"]:
abort(500)
return redirect("<https://<app-url>")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment