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, bypass={"/health"}) # 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
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 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 | |
Functions
protect_app(app, bypass=None)
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 |
bypass
|
set[str] | None
|
Optional set of paths that skip authentication (e.g. {"/health", "/ready"}). Trailing slashes are ignored when matching, so "/health" will also match "/health/". |
None
|
Example
app = FastAPI() auth = GradioAuth() auth.protect_app(app, bypass={"/health"})
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.name}"
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, bypass={"/health"}) # Protects entire app!
def greet(name: str, request: gr.Request):
user = auth.get_auth_user(request)
return f"Hello {name}! Logged in as {user.name}"
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://public.gds-idea.io/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
PermissionErroron authorisation failure
Gradio + FastAPI with protect_app():
- Middleware redirects to
redirect_urlbefore Gradio functions execute - User stored in
request.state.userfor efficiency - Use the
bypassparameter to exclude paths like health checks (e.g.bypass={"/health"})
Development Mode
Enable dev mode for local development without ALB. See Development Mode for full details.
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.name} ({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, bypass={"/health"})
def greet(name: str, request: gr.Request):
user = auth.get_auth_user(request)
return f"Hello {name}! Logged in as {user.name}"
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.name}"
# 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")