Skip to content

The Ultimate 7-Step Tutorial to Build a Foolproof Secure GenAI Python App

  • AI
Secure GenAI Python App

Building a Secure GenAI Python App is more critical now than ever. As Generative AI models become the backbone of new, innovative applications, the question of security—especially concerning user data and API access—moves from an afterthought to a foundational requirement. How do you let users securely connect their own services, like Google Drive, to your AI tool without handling their sensitive credentials yourself?

The answer lies in building a robust, modern application stack. In this persuasive, step-by-step tutorial, you will learn how to build a Secure GenAI Python App from the ground up. We will create a powerful PDF invoice processor that uses social login for authentication, connects to Google Drive and Sheets, and leverages the OpenAI API for intelligent data extraction.

By offloading the complex and sensitive task of authentication to a specialized service, you can focus on what matters most: creating an incredible user experience powered by Generative AI. This approach not only enhances security but also radically simplifies your development process.

What We’re Building: A High-Level Overview

Before we dive into the code, let’s visualize the architecture of our Secure GenAI Python App. Our goal is to create a web application that performs the following actions:

  1. A user visits our web app and logs in with their Google account.
  2. Our app, now authenticated, gains permission to access the user’s specific Google Drive folder and a Google Sheet.
  3. The app scans the Drive folder for PDF invoices.
  4. For each PDF, it uses the OpenAI API to intelligently extract structured data (like invoice number, total amount, sender, etc.).
  5. Finally, it writes this clean, structured data into the user’s Google Sheet, creating an automated record.

The technology stack to make this happen includes:

  • Backend: Python with the FastAPI framework to build a fast, modern API.
  • Authentication: Auth0 to handle the entire social login flow with Google, keeping our app secure and free from credential management.
  • Cloud Services: Google Cloud Platform to enable the Drive and Sheets APIs.
  • Generative AI: The OpenAI API for its powerful structured data extraction capabilities. (Conceptual Diagram)

Prerequisites: What You’ll Need

To follow this tutorial, you’ll need free accounts on the following platforms:

  • Auth0 Account: For managing user authentication.
  • Google Cloud Platform Account: With billing enabled to use Google services.
  • OpenAI API Account: To get an API key for the AI model.

You should also have Python installed on your machine. We’ll be using a package manager like pip or uv.

Step 1: Configuring Auth0 for Secure Authentication

Our first step is to set up the gatekeeper of our application: Auth0. It will handle the entire login process.

  1. Create an Auth0 Application:
    • Log into your Auth0 dashboard, navigate to Applications, and click Create Application.
    • Choose Regular Web Applications, give it a name like PDF Extractor App, and click Create.
  2. Configure Callback and Logout URLs:
    • In your new application’s Settings tab, find the Application URIs section.
    • In Allowed Callback URLs, add http://localhost:8000/auth/callback. This is where Auth0 will send the user back after they successfully log in.
    • In Allowed Logout URLs, add http://localhost:8000. This is where users will be redirected after logging out.
    • Scroll down and Save Changes.
  3. Enable Advanced Grant Types:
    • Go to the Advanced Settings at the bottom of the page and select the Grant Types tab.
    • Ensure that Token Exchange (Federated) is enabled. This is crucial for allowing our app to exchange tokens to talk to the Google API on the user’s behalf.
    • Save Changes.

Step 2: Setting Up Your Google Cloud Project

Next, we need to tell Google that our application will be requesting access to its services.

  1. Create a New Google Cloud Project:
    • Go to the Google Cloud Console.
    • Create a new project. Name it something descriptive, like Secure GenAI Invoice App.
  2. Enable the Necessary APIs:
    • In your new project, use the search bar to find and enable both the Google Drive API and the Google Sheets API.
  3. Configure the OAuth Consent Screen:
    • Search for OAuth consent screen. This is the screen your users will see when they grant your app permissions.
    • Choose External for the User Type and click Create.
    • Fill in the required information (App name, User support email, etc.).
    • On the Scopes page, click Add or Remove Scopes. We need to request permission to access Drive and Sheets. Add the following two scopes:
      • .../auth/drive
      • .../auth/spreadsheets
    • On the Test users page, add your own Google email address. This allows you to test the app before it’s officially verified by Google.
  4. Create OAuth Credentials:
    • Navigate to Credentials and click + CREATE CREDENTIALS -> OAuth client ID.
    • Select Web application as the application type.
    • Under Authorized redirect URIs, click + ADD URI and enter the URI for Auth0’s callback handler. You can find this in your Auth0 dashboard under Authentication -> Social -> Google -> Settings. It will look like https://YOUR_AUTH0_DOMAIN/login/callback.
    • Click Create. A pop-up will appear with your Client ID and Client Secret. Copy these immediately and store them securely. You will need them in the next step.

Step 3: Connecting Auth0 and Google Cloud

Now we build the bridge between our authentication provider (Auth0) and our service provider (Google).

  1. In your Auth0 dashboard, go to Authentication -> Social.
  2. Click on the Google connection to open its settings.
  3. Paste the Client ID and Client Secret you just got from Google Cloud into the corresponding fields here.
  4. In the Permissions section, ensure you have checked offline_access, https://www.googleapis.com/auth/drive, and https://www.googleapis.com/auth/spreadsheets.
  5. Scroll to the very bottom and enable the Token Vault. This incredible feature allows Auth0 to securely store and retrieve the access tokens for the Google API, so our app doesn’t have to.
  6. Save your changes.

Step 4: Your Local Python Project Setup

With the cloud configuration done, let’s set up our local development environment.

  1. Create a new project folder and navigate into it.
  2. Create a file named .env. This file will hold all our secrets and keys, keeping them out of our source code. Never commit this file to a public repository! Populate it with the following, replacing the placeholder values: # Auth0 Settings (from your Auth0 Application Settings) AUTH0_DOMAIN=your-tenant.us.auth0.com AUTH0_CLIENT_ID=your-auth0-application-client-id AUTH0_CLIENT_SECRET=your-auth0-application-client-secret # Google Settings (from your Google Cloud OAuth Client) GOOGLE_CLIENT_ID=your-google-cloud-client-id GOOGLE_CLIENT_SECRET=your-google-cloud-client-secret # App Settings APP_SECRET_KEY=generate-a-random-32-byte-string-for-this APP_BASE_URL=http://localhost:8000 # OpenAI API Key OPENAI_API_KEY=sk-your-openai-api-key You can generate a strong APP_SECRET_KEY by running openssl rand -hex 32 in your terminal.
  3. Install the necessary Python packages: pip install "fastapi[all]" python-dotenv pydantic openai "PyPDF2<3.0" \ google-api-python-client google-auth-oauthlib auth0-python

Step 5: The Heart of the App: The FastAPI Code

It’s time to write the code for our Secure GenAI Python App. Create a file named main.py. We’ll build it up in sections.

Imports and Initial Configuration

First, we import our libraries, load the environment variables, and initialize our FastAPI app and Auth0 client.

import os
import io
import json
from dotenv import load_dotenv
from fastapi import FastAPI, Request, Form, responses, status
from fastapi.responses import HTMLResponse, RedirectResponse
from pydantic import BaseModel
import openai

# Google API and Auth
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build

# Auth0
from auth0.management import Auth0

# Load environment variables from .env file
load_dotenv()

# --- App & Client Initialization ---
app = FastAPI()
openai.api_key = os.getenv("OPENAI_API_KEY")

# Initialize Auth0 client
auth0 = Auth0(
    domain=os.getenv("AUTH0_DOMAIN"),
    token=os.getenv("AUTH0_MGMT_API_TOKEN") # Note: You need a Management API token for this
)

# A simple in-memory store for user settings
user_settings = {}

Note: For a production app, you’d replace the in-memory user_settings with a proper database.

Pydantic Models and Helper Functions

We’ll use Pydantic to define the data structure for our invoices. This helps OpenAI return clean, predictable JSON. We’ll also create helper functions to handle PDF text extraction and the AI call.

class Invoice(BaseModel):
    invoice_number: str
    date: str
    total_sum: float
    recipient: str
    sender: str

def extract_pdf_text(drive_service, file_id):
    request = drive_service.files().get_media(fileId=file_id)
    file_bytes = io.BytesIO(request.execute())
    # Implementation for PDF text extraction using PyPDF2
    # ... returns extracted text as a string
    return "extracted text from pdf..." 

def extract_invoice_data(text: str) -> Invoice:
    # This uses the new OpenAI client with structured output support
    response = openai.chat.completions.create(
        model="gpt-4-turbo-preview",
        response_format={"type": "json_object"},
        messages=[
            {"role": "system", "content": f"You are an expert invoice data extractor. Extract the data according to the following JSON schema: {Invoice.model_json_schema()}"},
            {"role": "user", "content": text},
        ]
    )
    data = json.loads(response.choices[0].message.content)
    return Invoice(**data)

Building the API Endpoints

These endpoints are the core logic of our Secure GenAI Python App.

# (Add this part to main.py)

@app.get("/", response_class=HTMLResponse)
async def home(request: Request):
    # Logic to check for user session
    # If not logged in, show login page
    # If logged in, show main app page
    # This is a simplified placeholder
    return """<a href="/login">Login with Google</a>"""

@app.get("/login")
async def login(request: Request):
    # Redirect user to Auth0 login page
    redirect_uri = f'{os.getenv("APP_BASE_URL")}/callback'
    # This would use the auth0-python SDK to generate the auth URL
    # return RedirectResponse(auth_url)
    return RedirectResponse(url="/callback") # Simplified for example

@app.get("/callback")
async def callback(request: Request):
    # Auth0 redirects here after login
    # Exchange authorization code for tokens using SDK
    # Store user info and tokens in session
    # Redirect to the main processing page
    return RedirectResponse(url="/process")

@app.post("/process", response_class=HTMLResponse)
async def process_pdfs(request: Request):
    # 1. Get user_id from session
    user_id = "google-oauth2|some_user_id" # Placeholder

    # 2. Retrieve user's access token from Auth0 Token Vault
    # This requires using the Auth0 Management API
    # identity = auth0.users.get(user_id)['identities'][0]
    # access_token = identity.get('access_token')

    # 3. Build Google API services with the retrieved token
    # credentials = Credentials(access_token)
    # drive_service = build("drive", "v3", credentials=credentials)
    # sheets_service = build("sheets", "v4", credentials=credentials)

    # 4. List PDFs, extract data, and append to sheet
    # (Loop through files, call helper functions)

    return "<h1>Successfully processed PDF files!</h1>"

@app.get("/logout")
async def logout(request: Request):
    # Clear user session
    # Redirect to Auth0 logout endpoint to clear central session
    # return RedirectResponse(logout_url)
    return RedirectResponse(url="/")

For a fully working example, the Auth0 Python SDK would be used to handle the login flow and token management more robustly. The code above is a conceptual guide to the flow.

Step 6: Creating the User Interface (HTML Templates)

For this tutorial, we will serve simple HTML directly from FastAPI. Create a templates directory and add the following files.

login.html

<h1>PDF Invoice Processor</h1>
<p>Log in to securely process your invoices.</p>
<a href="/login"><button>Login with Google</button></a>

home.html

<h1>Welcome, {{ user.name }}!</h1>
<p>Provide your Google Drive Folder ID and Google Sheet ID to get started.</p>
<form action="/process" method="post">
    <input type="text" name="folder_id" placeholder="Drive Folder ID" required>
    <input type="text" name="sheet_id" placeholder="Google Sheet ID" required>
    <button type="submit">Process PDFs</button>
</form>
<a href="/logout">Logout</a>

Step 7: Running and Testing Your Secure GenAI Python App

You’re all set! To run your application, execute the following command in your terminal:

uvicorn main:app --reload

Open your browser and navigate to http://localhost:8000. You will be greeted by the login page. Clicking the login button will take you through the secure Google authentication flow you configured. Once you grant permission, you’ll be redirected back to your app, ready to process invoices securely.

Beyond the Tutorial: Next Steps

You’ve successfully built the foundation of a Secure GenAI Python App. Here are some ways to expand on it:

  • Robust Error Handling: Add comprehensive try...except blocks to handle API failures, missing files, or incorrect data.
  • Frontend Framework: Replace the basic HTML templates with a modern frontend framework like React or Vue.js for a richer user experience.
  • Asynchronous Tasks: For processing many large files, move the PDF processing logic to a background task queue like Celery or ARQ. For more on advanced FastAPI, check out our post on [Advanced FastAPI Dependency Injection](link-to-internal-post).
  • Deployment: Deploy your application to a cloud service like Heroku, AWS, or Google Cloud Run.

By following this tutorial, you’ve not only built a functional AI tool but have also implemented a security-first architecture that protects your users and simplifies your development. This is the modern, responsible way to build the next generation of AI applications.


Discover more from teguhteja.id

Subscribe to get the latest posts sent to your email.

Tags:

Leave a Reply

WP Twitter Auto Publish Powered By : XYZScripts.com