Skip to content

StreamlitAuth

Authentication for Streamlit applications.

StreamlitAuth

Bases: BaseAuth

Authentication for Streamlit apps.

Example

import streamlit as st from cognito_auth.streamlit import StreamlitAuth

Auto-loads from environment variables

auth = StreamlitAuth() user = auth.get_auth_user()

st.write(f"Welcome {user.email}!") st.write(f"Groups: {', '.join(user.groups)}")

Source code in src/cognito_auth/streamlit.py
class StreamlitAuth(BaseAuth):
    """
    Authentication for Streamlit apps.

    Example:
        import streamlit as st
        from cognito_auth.streamlit import StreamlitAuth

        # Auto-loads from environment variables
        auth = StreamlitAuth()
        user = auth.get_auth_user()

        st.write(f"Welcome {user.email}!")
        st.write(f"Groups: {', '.join(user.groups)}")
    """

    def get_auth_user(self) -> User:
        """
        Get the authenticated and authorised user for this request.

        Validates user from Cognito headers and checks authorisation.
        Stops execution with error message if authentication or authorisation fails.

        Note: Unlike other frameworks, Streamlit has no native redirect function.
        This method displays an error message and stops execution using st.stop(),
        which prevents any code after this call from running.

        Returns:
            Authenticated and authorised User

        Example:
            auth = StreamlitAuth()
            user = auth.get_auth_user()
            st.write(f"Hello {user.email}")
        """
        try:
            headers = st.context.headers
            user = self._get_user_from_headers(dict(headers))

            if not self._is_authorised(user):
                st.error(
                    "🔒 Access denied. You don't have permission to access "
                    "this application."
                )
                st.info(
                    "Please contact your administrator if you believe this is an error."
                )
                st.stop()

            return user

        except Exception:
            st.error("🔒 Authentication failed.")
            st.info(
                "Unable to verify your identity. Please try again or contact support."
            )
            st.stop()

Functions

get_auth_user()

Get the authenticated and authorised user for this request.

Validates user from Cognito headers and checks authorisation. Stops execution with error message if authentication or authorisation fails.

Note: Unlike other frameworks, Streamlit has no native redirect function. This method displays an error message and stops execution using st.stop(), which prevents any code after this call from running.

Returns:

Type Description
User

Authenticated and authorised User

Example

auth = StreamlitAuth() user = auth.get_auth_user() st.write(f"Hello {user.email}")

Source code in src/cognito_auth/streamlit.py
def get_auth_user(self) -> User:
    """
    Get the authenticated and authorised user for this request.

    Validates user from Cognito headers and checks authorisation.
    Stops execution with error message if authentication or authorisation fails.

    Note: Unlike other frameworks, Streamlit has no native redirect function.
    This method displays an error message and stops execution using st.stop(),
    which prevents any code after this call from running.

    Returns:
        Authenticated and authorised User

    Example:
        auth = StreamlitAuth()
        user = auth.get_auth_user()
        st.write(f"Hello {user.email}")
    """
    try:
        headers = st.context.headers
        user = self._get_user_from_headers(dict(headers))

        if not self._is_authorised(user):
            st.error(
                "🔒 Access denied. You don't have permission to access "
                "this application."
            )
            st.info(
                "Please contact your administrator if you believe this is an error."
            )
            st.stop()

        return user

    except Exception:
        st.error("🔒 Authentication failed.")
        st.info(
            "Unable to verify your identity. Please try again or contact support."
        )
        st.stop()

Quick Start

import streamlit as st
from cognito_auth.streamlit import StreamlitAuth

# Auto-loads from environment variables
auth = StreamlitAuth()
user = auth.get_auth_user()

st.write(f"Welcome {user.email}!")
st.write(f"Groups: {', '.join(user.groups)}")

Configuration

StreamlitAuth inherits from BaseAuth and accepts these parameters:

  • authoriser (optional): Pre-configured Authoriser instance. If not provided, auto-loads from environment variables
  • redirect_url (optional): Not used in Streamlit (defaults to "https://gds-idea.click/401.html")
  • region (optional): AWS region (default: "eu-west-2")
from cognito_auth import Authoriser
from cognito_auth.streamlit import StreamlitAuth

# Custom configuration
authoriser = Authoriser.from_lists(allowed_groups=["developers"])
auth = StreamlitAuth(
    authoriser=authoriser,
    region="us-east-1"
)

Behavior

Unlike other frameworks, Streamlit cannot redirect users. When authentication or authorisation fails, get_auth_user():

  1. Displays an error message using st.error()
  2. Displays an info message using st.info()
  3. Stops execution using st.stop()

This prevents any code after get_auth_user() from running for unauthorised users.

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

import streamlit as st
from cognito_auth.streamlit import StreamlitAuth

# Initialize auth
auth = StreamlitAuth()

# This line protects your entire app
user = auth.get_auth_user()

# Only authenticated and authorised users reach here
st.title("Protected Dashboard")
st.write(f"Logged in as: {user.email}")

# Use user information in your app
if user.is_admin:
    st.write("🔑 You have admin access")

for group in user.groups:
    st.write(f"📁 {group}")