Guards

Guards decide whether a request may continue. They run after middleware and before interceptors. A guard returns a boolean — true allows the request to proceed, false rejects it with an unauthorized response.

The Guard trait

use ferrite_framework::{Guard, RequestCtx, async_trait};

pub struct AdminGuard;

#[async_trait]
impl Guard for AdminGuard {
    async fn can_activate(&self, ctx: &RequestCtx) -> bool {
        // inspect the request (headers, query, state...) and decide
        ctx.header_str("X-Admin-Token").is_some()
    }
}

The rejection response is generated by the pipeline automatically.

Applying guards

use ferrite_framework::{use_guards, get, Json, HttpError};

#[impl_controller]
impl UsersController {
    #[use_guards(AdminGuard)]
    #[get("/{id}/admin")]
    pub async fn admin(&self, Path(id): Path<i64>) -> Result<Json<User>, HttpError> { /* ... */ }
}

Multiple guards are allowed — all of them must pass:

#[use_guards(AuthGuard, AdminGuard)]

Guards can also be applied to an entire controller by annotating the impl block:

#[impl_controller]
#[use_guards(AuthGuard)]
impl UsersController { /* ... */ }

Guard order

Middleware → **Guards** → Interceptors(before) → Pipes → Handler

Guards never see the transformed body; they inspect the raw RequestCtx. Chain multiple guards left-to-right — they are evaluated in declaration order and any failure short-circuits.

Built-in guards

  • ferrite-auth-jwt ships AuthGuard, which verifies a Authorization: Bearer <token> HS256 token. See Authentication (JWT).
  • ferrite-throttler ships ThrottlerGuard, which rate limits by IP/token. See Rate limiting.

Notes

  • Guards that need dependencies use #[injectable] + #[inject] like any provider.
  • Guard metadata (guard_types) is recorded per-route and consumed by ferrite-swagger to add 401 + security schemes to generated specs.

Next steps