Skip to main content

Crate churust_auth

Crate churust_auth 

Source
Expand description

Authentication plugins for the Churust web framework.

This crate provides ready-made authentication schemes — Bearer tokens, HTTP Basic credentials, and Jwt bearer tokens — plus the Principal<P> extractor used to require and read the authenticated user inside a handler.

§Authentication vs. authorization

An auth plugin only authenticates: it inspects the incoming Authorization header, verifies the credentials, and — on success — inserts a principal value (your own user/claims type) into the call’s extensions. It never rejects a request on its own. If the credentials are missing or invalid, the plugin simply leaves no principal behind.

Authorization — actually requiring a logged-in user — is type-driven and explicit: a handler asks for a Principal<P> argument. When a principal of type P is present the handler runs; when it is absent the extractor returns 401 Unauthorized with a WWW-Authenticate: Bearer challenge before the handler body is ever entered. Routes that do not ask for a Principal stay public.

All schemes are constructed through the Auth namespace and installed with AppBuilder::install. The principal type P you choose is what later handlers extract; only one principal type can be resolved per call (the most recently inserted value of a given type wins).

§Example

Protect a route with bearer-token auth. The /me handler only runs when a valid token resolved to a User principal; otherwise the Principal extractor short-circuits with 401.

use churust_core::{Churust, TestClient};
use churust_auth::{Auth, Principal};

#[derive(Clone)]
struct User {
    name: String,
}

let app = Churust::server()
    .install(Auth::bearer(|token: String| async move {
        (token == "s3cret").then(|| User { name: "ana".into() })
    }))
    .routing(|r| {
        r.get("/me", |Principal(u): Principal<User>| async move {
            format!("hello {}", u.name)
        });
    })
    .build();

// A valid token reaches the handler.
let ok = TestClient::new(app.clone())
    .get("/me")
    .header("authorization", "Bearer s3cret")
    .send()
    .await;
assert_eq!(ok.status().as_u16(), 200);
assert_eq!(ok.text(), "hello ana");

// No credentials => 401 with a challenge, handler never runs.
let denied = TestClient::new(app).get("/me").send().await;
assert_eq!(denied.status().as_u16(), 401);
assert_eq!(denied.header("www-authenticate"), Some("Bearer"));

Structs§

Auth
Constructor namespace for the authentication scheme plugins.
Basic
HTTP Basic authentication plugin produced by Auth::basic.
Bearer
Bearer-token authentication plugin produced by Auth::bearer.
Jwt
JWT bearer-token authentication plugin produced by Auth::jwt_hs256.
Principal
Handler argument that requires and yields the authenticated principal of type P.