pub struct Principal<P>(pub P);Expand description
Handler argument that requires and yields the authenticated principal of
type P.
Principal<P> is the bridge between authenticating (a scheme plugin
inserting a principal into the call) and authorizing (a handler demanding
one). Add it as a handler parameter to make that route require auth: the
extractor looks up a value of type P previously stored on the call by an
auth plugin such as Auth::bearer, Auth::basic, or Auth::jwt_hs256.
The inner value is exposed as the public tuple field, so you typically
destructure it directly in the parameter list, e.g.
|Principal(user): Principal<User>|.
§Type parameter
P— the principal type you chose when installing the auth scheme. It must beClone + Send + Sync + 'static. This is the same type the plugin’sverifyclosure returns (or, forJwt, the decoded claims type).
§Errors
If no principal of type P was inserted for this call (no/invalid/expired
credentials, or a mismatched principal type) the extractor returns
401 Unauthorized with a WWW-Authenticate: Bearer response header, and the
handler body never runs.
§Examples
use churust_core::{Churust, TestClient};
use churust_auth::{Auth, Principal};
#[derive(Clone)]
struct User {
id: u64,
}
let app = Churust::server()
.install(Auth::bearer(|tok: String| async move {
(tok == "ok").then(|| User { id: 7 })
}))
.routing(|r| {
r.get("/id", |Principal(u): Principal<User>| async move {
u.id.to_string()
});
})
.build();
let res = TestClient::new(app)
.get("/id")
.header("authorization", "Bearer ok")
.send()
.await;
assert_eq!(res.status().as_u16(), 200);
assert_eq!(res.text(), "7");Tuple Fields§
§0: PThe authenticated principal value inserted by the auth scheme.