GradioAuth
Authentication for Gradio applications.
GradioAuth
Bases: BaseAuth
Authentication for Gradio apps.
Gradio can run standalone or mounted on FastAPI. This class supports both.
Example (Standalone Gradio): import gradio as gr from cognito_auth.gradio import GradioAuth
auth = GradioAuth()
def greet(name: str, request: gr.Request):
user = auth.get_auth_user(request)
return f"Hello {name}! Logged in as {user.email}"
demo = gr.Interface(greet, "text", "text")
demo.launch()
Example (Gradio + FastAPI): import gradio as gr from fastapi import FastAPI from cognito_auth.gradio import GradioAuth
app = FastAPI()
auth = GradioAuth()
auth.protect_app(app) # Protect entire app!
def greet(name: str, request: gr.Request):
user = auth.get_auth_user(request)
return f"Hello {name}! Logged in as {user.email}"
demo = gr.Interface(greet, "text", "text")
app = gr.mount_gradio_app(app, demo, path="/")
Source code in src/cognito_auth/gradio.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 | |
Functions
protect_app(app)
Protect a FastAPI app that has Gradio mounted on it.
Use this when mounting Gradio onto FastAPI. It adds middleware to validate authentication before every request.
NOTE: This only works when Gradio is mounted on FastAPI. For standalone Gradio apps, use get_auth_user() in each function instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app
|
FastAPI
|
FastAPI application instance (before mounting Gradio) |
required |
Example
app = FastAPI() auth = GradioAuth() auth.protect_app(app)
def greet(name: str, request: gr.Request): user = auth.get_auth_user(request) return f"Hello {name} ({user.email})"
demo = gr.Interface(greet, "text", "text") app = gr.mount_gradio_app(app, demo, path="/")
Source code in src/cognito_auth/gradio.py
get_auth_user(request)
Get the authenticated and authorised user for this request.
For standalone Gradio: Validates user from request headers. For Gradio + FastAPI with protect_app(): Retrieves pre-validated user.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
Gradio Request object (pass as parameter to your function) |
required |
Returns:
| Type | Description |
|---|---|
User
|
Authenticated and authorised User |
Raises:
| Type | Description |
|---|---|
PermissionError
|
If user is not authorised |
Exception
|
If authentication fails |
Example (Standalone): def greet(name: str, request: gr.Request): user = auth.get_auth_user(request) return f"Hello {name} ({user.email})"
Example (With FastAPI): auth.protect_app(app)
def greet(name: str, request: gr.Request):
user = auth.get_auth_user(request)
return f"Hello {name} ({user.email})"
Source code in src/cognito_auth/gradio.py
Quick Start
Standalone Gradio
import gradio as gr
from cognito_auth.gradio import GradioAuth
auth = GradioAuth()
def greet(name: str, request: gr.Request):
user = auth.get_auth_user(request)
return f"Hello {name}! Logged in as {user.email}"
demo = gr.Interface(greet, "text", "text")
demo.launch()
Gradio + FastAPI (Recommended)
import gradio as gr
from fastapi import FastAPI
from cognito_auth.gradio import GradioAuth
app = FastAPI()
auth = GradioAuth()
auth.protect_app(app) # Protects entire app!
def greet(name: str, request: gr.Request):
user = auth.get_auth_user(request)
return f"Hello {name}! Logged in as {user.email}"
demo = gr.Interface(greet, "text", "text")
app = gr.mount_gradio_app(app, demo, path="/")
Configuration
GradioAuth inherits from BaseAuth and accepts these parameters:
authoriser(optional): Pre-configured Authoriser instance. If not provided, auto-loads from environment variablesredirect_url(optional): Where to redirect unauthorised users (default: "https://gds-idea.click/401.html")region(optional): AWS region (default: "eu-west-2")
from cognito_auth import Authoriser
from cognito_auth.gradio import GradioAuth
# Custom configuration
authoriser = Authoriser.from_lists(allowed_groups=["developers"])
auth = GradioAuth(
authoriser=authoriser,
redirect_url="https://myapp.com/unauthorised",
region="us-east-1"
)
Behavior
GradioAuth works in two modes:
Standalone Gradio:
- User must be passed to get_auth_user(request) in each function
- Raises PermissionError on authorisation failure
Gradio + FastAPI with protect_app():
- Middleware redirects to redirect_url before Gradio functions execute
- User stored in request.state.user for efficiency
Development Mode
Enable dev mode for local development without ALB:
When dev mode is enabled and headers are missing, get_auth_user() returns a mock user instead of failing.
Customizing the Mock User
To customize the mock user returned in dev mode, create a dev-mock-user.json file in your project root:
{
"email": "developer@example.com",
"sub": "12345678-1234-1234-1234-123456789abc",
"username": "12345678-1234-1234-1234-123456789abc",
"groups": ["developers", "users"]
}
The mock user will use these values instead of the defaults. This is useful for testing different authorisation scenarios.
Available fields:
- email - Mock user's email address
- sub - Mock user's Cognito subject (UUID)
- username - Mock user's username (usually same as sub)
- groups - Mock user's Cognito groups for authorisation testing
See dev-mock-user.example.json in the repository for a complete template with comments.
Alternative config location:
You can specify a custom path via environment variable:
Complete Example
Standalone Gradio
import gradio as gr
from cognito_auth.gradio import GradioAuth
auth = GradioAuth()
def greet(name: str, request: gr.Request):
user = auth.get_auth_user(request)
info = f"""
Hello {name}!
Logged in as: {user.email}
Groups: {', '.join(user.groups)}
Admin: {'Yes' if user.is_admin else 'No'}
"""
return info
demo = gr.Interface(
fn=greet,
inputs=gr.Textbox(label="Your Name"),
outputs=gr.Textbox(label="Greeting")
)
demo.launch()
Gradio + FastAPI
import gradio as gr
from fastapi import FastAPI
from cognito_auth.gradio import GradioAuth
app = FastAPI()
# Initialize and protect entire app
auth = GradioAuth()
auth.protect_app(app)
def greet(name: str, request: gr.Request):
user = auth.get_auth_user(request)
return f"Hello {name}! Logged in as {user.email}"
def admin_panel(request: gr.Request):
user = auth.get_auth_user(request)
if not user.is_admin:
return "⛔ Admin access required"
return f"👑 Admin panel for {user.email}"
# Public interface
demo_public = gr.Interface(greet, "text", "text")
# Admin interface
demo_admin = gr.Interface(
fn=admin_panel,
inputs=None,
outputs="text"
)
# Mount both interfaces
app = gr.mount_gradio_app(app, demo_public, path="/")
app = gr.mount_gradio_app(app, demo_admin, path="/admin")