Real Authorization in Leptos: Protect Your Server Functions, Not Just Your Routes

Automated English translation of the original Spanish article. Code examples keep their original identifiers.

Redirecting to login on the frontend protects nothing: every Leptos #[server] is a public HTTP endpoint, and real authorization must live on the server. In this article, we’ll see how to shield a full-stack application built with Leptos and Axum, with code you can explore on the feat/autorizacion-server-functions branch of user-leptos-app.

The Illusion of Security with Server Functions

In the previous article, we structured a full-stack application with Leptos (updated in this installment to Leptos 0.9.0-rc0): SSR, WASM hydration, SQLite, and session cookie authentication.

Note: Leptos 0.9 is still a release candidate (0.9.0-rc0), so some APIs might change before the final release. If you are using the stable 0.8 series, check the differences before copying the code.

We had a /users page protected with a very common frontend pattern:

// Redirección client-side si no hay sesión
Effect::new(move |_| {
    if let AuthState::Unauthenticated = auth.state.get() {
        navigate("/login", Default::default());
    }
});

It seems like everything is under control: if an unauthenticated user visits /users, the UI kicks them out to /login.

The problem is that every #[server] macro generates a public HTTP endpoint, for example POST /api/delete_user. Running this in a terminal is all it takes:

curl -i -X POST http://127.0.0.1:3000/api/delete_user \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "id=1"

And the user was deleted. The function didn’t verify who was making the request or what role they had.

And the user was deleted. The function didn’t verify who was making the request or what role they had.
Golden rule: server functions are not private local function calls, but HTTP endpoints exposed to the world. Protecting the UI is UX; real security happens on the server.

The rest of this article walks through the pieces we used to close that loophole: typed errors, shared policies, guards, an api layer with a standard per-function flow, pool injection, and tests that attack the API just like an external client would.

Typed Errors with Real HTTP Status Codes

By default, errors in Leptos often end up as a generic ServerFnError::new("Error..."), returning an HTTP 500 with plain text. As a result, the client cannot distinguish an expired session from a missing permission.

The solution is a custom enum, AppError, which implements FromServerFnError and maps each variant to its corresponding HTTP status code:

// src/domain/error.rs
use http::StatusCode;
use leptos::server_fn::codec::JsonEncoding;
use leptos::server_fn::error::{FromServerFnError, ServerFnErrorErr};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, thiserror::Error)]
pub enum AppError {
    #[error("Debes iniciar sesión para continuar")]
    Unauthorized, // HTTP 401

    #[error("{0}")]
    Forbidden(String), // HTTP 403

    #[error("{0}")]
    NotFound(String), // HTTP 404

    #[error("{0}")]
    Validation(String), // HTTP 422

    #[error("{0}")]
    Conflict(String), // HTTP 409

    #[error("Error interno del servidor")]
    Internal, // HTTP 500

    #[error("Error de comunicación con el servidor: {0}")]
    ServerFn(String),
}

impl AppError {
    pub fn forbidden(msg: impl Into<String>) -> Self {
        Self::Forbidden(msg.into())
    }
}

impl FromServerFnError for AppError {
    type Encoder = JsonEncoding;

    fn from_server_fn_error(value: ServerFnErrorErr) -> Self {
        AppError::ServerFn(value.to_string())
    }

    fn status_code(&self) -> StatusCode {
        match self {
            AppError::Unauthorized => StatusCode::UNAUTHORIZED,
            AppError::Forbidden(_) => StatusCode::FORBIDDEN,
            AppError::NotFound(_) => StatusCode::NOT_FOUND,
            AppError::Validation(_) => StatusCode::UNPROCESSABLE_ENTITY,
            AppError::Conflict(_) => StatusCode::CONFLICT,
            AppError::Internal | AppError::ServerFn(_) => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }
}

With this, a 401 means “log in” and a 403 means “you are authenticated, but lack permission.” Furthermore, on the server we implement From<sqlx::Error> for AppError to log SQL failures internally and consistently return AppError::Internal—except for UNIQUE constraint violations, which translate to AppError::Conflict (409)—preventing database schema details from leaking to the client.

Pure Policies in the Domain

To avoid duplicating the “who can do what” logic, we define it as pure functions in domain/policy.rs. By living in the isomorphic domain, they are shared across client and server:

  • The server runs them to enforce security.
  • The frontend (WASM) runs them to hide buttons or disable actions (UX).
// src/domain/policy.rs
pub fn can_manage_users(actor: &User) -> Result<(), AppError> {
    match actor.role {
        UserRole::Admin => Ok(()),
        UserRole::User => Err(AppError::forbidden(
            "Solo los administradores pueden gestionar usuarios",
        )),
    }
}

pub fn can_delete_user(actor: &User, target_id: i64) -> Result<(), AppError> {
    can_manage_users(actor)?;
    if actor.id == target_id {
        return Err(AppError::forbidden("No puedes eliminar tu propia cuenta"));
    }
    Ok(())
}

On the frontend, we reuse the exact same function to adapt the view and react per variant when a call fails:

// src/frontend/users/list_page.rs
let can_manage = Memo::new(move |_| {
    auth.user()
        .map(|u| policy::can_manage_users(&u).is_ok())
        .unwrap_or(false)
});

// Y al renderizar el Resource de usuarios:
Err(AppError::Unauthorized) => view! {
    <div class="error-state">
        <p>"Tu sesión ha expirado. "</p>
        <a href="/login" class="btn btn-primary">"Iniciar sesión"</a>
    </div>
}.into_any(),

A single source of truth: if the rule changes tomorrow, it changes in one place, and both the button and the endpoint respect it.

Reusable Server Guards

On the server, we create simple helpers that extract the cookie (HttpOnly, SameSite=Lax, and Secure in production), validate the session in SQLite, and return the user. Each one builds on the previous one:

// src/server/guards.rs
pub async fn current_user() -> Result<Option<User>, AppError> {
    let Some(session_id) = session::read_cookie().await else {
        return Ok(None);
    };

    let pool = db::pool()?;
    let user = session::find_user(&pool, &session_id).await?;
    if user.is_none() {
        session::clear_cookie();
    }
    Ok(user)
}

pub async fn require_user() -> Result<User, AppError> {
    current_user().await?.ok_or(AppError::Unauthorized)
}

pub async fn require_admin() -> Result<User, AppError> {
    let user = require_user().await?;
    policy::can_manage_users(&user)?;
    Ok(user)
}

current_user does not fail if there is no session: it returns None (and cleans up the browser cookie if it has expired). require_user turns that absence into a 401, and require_admin reuses the domain policy to produce a 403.

src/api: The Security Boundary and Its Standard Flow

To prevent access control from tangling with SQL queries, we separate concerns into two modules:

  • src/api/: Contains all server functions (#[server]). It is the single entry point from the outside.
  • src/server/: Pure repositories (users, session) that assume the caller has already validated permissions.

With that clear boundary, every server function follows the same sequence: authenticate, authorize, and only then execute.

// src/api/users.rs
#[server(prefix = "/api", endpoint = "delete_user")]
pub async fn delete_user(id: i64) -> Result<(), AppError> {
    // 1. Autenticación y rol base (401 sin sesión, 403 si no es admin)
    let actor = guards::require_admin().await?;

    // 2. Regla específica (403 si intenta borrarse a sí mismo)
    policy::can_delete_user(&actor, id)?;

    // 3. Ejecución en base de datos
    let pool = db::pool()?;
    session::delete_for_user(&pool, id).await?;
    users::delete(&pool, id).await
}

The same curl from earlier now receives a 401 without a cookie and a 403 with a regular user session. In addition, when deleting a user, we immediately purge their active sessions. Because the pattern is always identical, auditing a new endpoint simply comes down to looking at its first few lines.

Saying Goodbye to OnceLock: Pool via Context

Previously, the database pool lived in a static OnceLock<SqlitePool>. A global like that hinders automated testing because all tests share the same state.

Now we use leptos_routes_with_context in Axum to inject the pool into every request (both for SSR and server functions):

// src/server/app.rs
pub fn build_router(leptos_options: LeptosOptions, pool: SqlitePool) -> Router {
    let routes = generate_route_list(App);

    Router::new()
        .leptos_routes_with_context(
            &leptos_options,
            routes,
            move || provide_context(pool.clone()),
            {
                let leptos_options = leptos_options.clone();
                move || shell(leptos_options.clone())
            },
        )
        .fallback(leptos_axum::file_and_error_handler(shell))
        .with_state(leptos_options)
}

In any server function, calling db::pool(), which retrieves use_context::<SqlitePool>(), is all it takes. That way, each test builds its own router with an isolated sqlite::memory: database (configured with max_connections(1) so all queries within the test share that same in-memory database).

Protected Routes in SSR: Flicker-Free Redirection

The initial Effect only runs in the browser: it sends the page first and waits for WASM to load before redirecting. To let the server decide right from the start, AuthContext now fetches the session with a Resource reactive to login and logout actions, exposing is_authenticated() -> Option<bool> (None while loading).

That fits seamlessly with ProtectedRoute and SsrMode::Async:

// src/app.rs
<ProtectedRoute
    path=StaticSegment("users")
    view=UsersListPage
    condition=move || auth.is_authenticated()
    redirect_path=|| "/login"
    ssr=SsrMode::Async
/>

Leptos resolves the session Resource during SSR and directly issues an HTTP 302 Found to /login if there is no session, without ever rendering the page. It’s still UX: data security is guaranteed by the server functions in src/api.

Verification with Real Integration Tests

To verify that the vulnerability is closed, tests hit the Axum router directly using tower::ServiceExt::oneshot, emulating an external HTTP client just like the curl command at the beginning:

// tests/authorization.rs
#[tokio::test]
async fn anonymous_cannot_delete_users() {
    let app = TestApp::new().await;
    let (status, _, _) = app.post("delete_user", "id=2", None).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn regular_user_cannot_delete_users() {
    let app = TestApp::new().await;
    let cookie = app.login("alice", "alice123").await;
    let (status, _, _) = app.post("delete_user", "id=1", Some(&cookie)).await;
    assert_eq!(status, StatusCode::FORBIDDEN);
}

They run with cargo test --features ssr. In total, there are 15 integration tests (plus unit tests for domain::policy) covering:

  • Anonymous calls (401), forged cookies, and expired sessions in SQLite.
  • Non-permitted users attempting to delete or promote themselves to Admin (403).
  • Admins attempting to delete themselves or remove their own role (403).
  • Immediate session revocation upon logout or user deletion.
  • Identical responses (422) and dummy hash verification during login to prevent user enumeration through error messages or response timing.

Where We Stand

The key takeaway fits in one line: every #[server] is a public door, so each one needs its own access control. The pattern we used boils down to:

  1. Typed errors (AppError) so the client can distinguish between 401, 403, 409, and 422 without leaking internal errors.
  2. Pure domain policies, shared across server (security) and frontend (UX).
  3. api layer + guards, applying the same flow at the start of every function.
  4. Context-injected pool, eliminating globals to properly isolate each test.
  5. Real HTTP tests against the router, thinking like an external client rather than from the UI.

You can check out and run the full code in the feat/autorizacion-server-functions branch of user-leptos-app. If you spot a test case we missed, let me know in the comments.

Keep on coding.