Skip to content

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
class GradioAuth(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="/")
    """

    def protect_app(self, app: FastAPI) -> 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.

        Args:
            app: FastAPI application instance (before mounting Gradio)

        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="/")
        """

        class AuthMiddleware(BaseHTTPMiddleware):
            def __init__(self, app, auth_instance):
                super().__init__(app)
                self.auth = auth_instance

            async def dispatch(self, request, call_next):
                """Validate authentication before every request."""
                try:
                    headers = dict(request.headers)
                    user = self.auth._get_user_from_headers(headers)

                    if not self.auth._is_authorised(user):
                        return RedirectResponse(url=self.auth.redirect_url)

                    # Store user in request state
                    request.state.user = user

                    return await call_next(request)

                except Exception:
                    return RedirectResponse(url=self.auth.redirect_url)

        app.add_middleware(AuthMiddleware, auth_instance=self)

    def get_auth_user(self, request: Request) -> User:
        """
        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.

        Args:
            request: Gradio Request object (pass as parameter to your function)

        Returns:
            Authenticated and authorised User

        Raises:
            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})"
        """
        # If protect_app() was used, user is stored in request.state
        if hasattr(request, "state") and hasattr(request.state, "user"):
            return request.state.user

        # Otherwise, validate on-demand (standalone Gradio)
        headers = dict(request.headers)
        user = self._get_user_from_headers(headers)

        if not self._is_authorised(user):
            raise PermissionError(
                "Access denied. You don't have permission to access this resource."
            )

        return user

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
def protect_app(self, app: FastAPI) -> 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.

    Args:
        app: FastAPI application instance (before mounting Gradio)

    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="/")
    """

    class AuthMiddleware(BaseHTTPMiddleware):
        def __init__(self, app, auth_instance):
            super().__init__(app)
            self.auth = auth_instance

        async def dispatch(self, request, call_next):
            """Validate authentication before every request."""
            try:
                headers = dict(request.headers)
                user = self.auth._get_user_from_headers(headers)

                if not self.auth._is_authorised(user):
                    return RedirectResponse(url=self.auth.redirect_url)

                # Store user in request state
                request.state.user = user

                return await call_next(request)

            except Exception:
                return RedirectResponse(url=self.auth.redirect_url)

    app.add_middleware(AuthMiddleware, auth_instance=self)

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
def get_auth_user(self, request: Request) -> User:
    """
    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.

    Args:
        request: Gradio Request object (pass as parameter to your function)

    Returns:
        Authenticated and authorised User

    Raises:
        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})"
    """
    # If protect_app() was used, user is stored in request.state
    if hasattr(request, "state") and hasattr(request.state, "user"):
        return request.state.user

    # Otherwise, validate on-demand (standalone Gradio)
    headers = dict(request.headers)
    user = self._get_user_from_headers(headers)

    if not self._is_authorised(user):
        raise PermissionError(
            "Access denied. You don't have permission to access this resource."
        )

    return user

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()
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 variables
  • redirect_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:

export COGNITO_AUTH_DEV_MODE=true

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:

export COGNITO_AUTH_DEV_CONFIG=/path/to/your/mock-user.json

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")