Module gate

Module gate 

Source
Expand description

Gate implementation for protecting axum routes with JWT authentication.

The Gate provides a high-level API for adding authentication and authorization to your axum routes using JWT cookies or bearer tokens. It supports role-based access control, group-based access control, and fine-grained permission systems.

§Basic Usage

use axum::{routing::get, Router};
use axum_gate::prelude::*;
use std::sync::Arc;

let jwt_codec = Arc::new(JsonWebToken::<JwtClaims<Account<Role, Group>>>::default());
let cookie_template = CookieTemplate::recommended()
    .name("auth-token")
    .persistent(cookie::time::Duration::hours(24));

let app = Router::<()>::new()
    .route("/admin", get(protected_handler))
    .layer(
        Gate::cookie("my-app", jwt_codec)
            .with_policy(AccessPolicy::<Role, Group>::require_role(Role::Admin))
            .with_cookie_template(cookie_template)
    );

§Access Control Examples

§Role-Based Access

// Allow only Admin role
let gate = Gate::cookie("my-app", Arc::clone(&jwt_codec))
    .with_policy(AccessPolicy::<Role, Group>::require_role(Role::Admin));

// Allow Admin or Moderator roles
let gate = Gate::cookie("my-app", Arc::clone(&jwt_codec))
    .with_policy(
        AccessPolicy::<Role, Group>::require_role(Role::Admin)
            .or_require_role(Role::Moderator)
    );

§Hierarchical Access

// Allow User role and all supervisor roles (Reporter, Moderator, Admin)
let gate = Gate::cookie("my-app", jwt_codec)
    .with_policy(AccessPolicy::<Role, Group>::require_role_or_supervisor(Role::User));

§Permission-Based Access

let gate = Gate::cookie("my-app", jwt_codec)
    .with_policy(
        AccessPolicy::<Role, Group>::require_permission(PermissionId::from("read:api"))
    );

§Bearer Gate (JWT)

Strict bearer (JWT) example:

let jwt = Arc::new(JsonWebToken::<JwtClaims<Account<Role, Group>>>::default());
let app = Router::<()>::new()
    .route("/admin", get(handler))
    .layer(
        Gate::bearer("my-app", Arc::clone(&jwt))
            .with_policy(AccessPolicy::<Role, Group>::require_role(Role::Admin))
    );

Optional user context (never blocks; handlers must enforce access):

let jwt = Arc::new(JsonWebToken::<JwtClaims<Account<Role, Group>>>::default());
let gate = Gate::bearer::<JsonWebToken<JwtClaims<Account<Role, Group>>>, Role, Group>("my-app", jwt).allow_anonymous_with_optional_user();
// Inserts Option<Account<Role, Group>> and Option<RegisteredClaims> into request extensions.

Modules§

bearer
Bearer gate implementation supporting two compile-time distinct modes:
cookie
Cookie-based JWT authentication gate for browser apps (HTTP-only cookies).
oauth2
OAuth2 login flow with /login and /callback routes. Cookie templates are validated when building routes to fail fast on insecure combinations.

Structs§

Gate
Main entry point for creating authentication gates.