Skip to main content

fastauth_plugin_jwt/
lib.rs

1//! JWTs for [fastauth](https://github.com/lassejlv/fastauth), like Better Auth's `jwt` plugin:
2//! services that can't share the session store check a signed token against a public key set
3//! instead of calling back to the auth server.
4//!
5//! - `GET /token` answers `{ "token": "<jwt>" }` for the request's session.
6//! - `GET /jwks` lists the public keys as a JWKS. The first key is created on first use.
7//! - `/get-session` also answers with the token in a `set-auth-jwt` header, listed in
8//!   `Access-Control-Expose-Headers`.
9//!
10//! Tokens are EdDSA (Ed25519) by default; [`JwtAlgorithm::ES256`] and
11//! [`JwtAlgorithm::RS256`] are options. They carry the user, `sub` (the user id), `iat`,
12//! `exp` (15 minutes), and `iss` and `aud` (the base URL unless configured). Private keys
13//! are stored encrypted with the app secret. With [`Jwt::rotation_interval`], keys expire
14//! and a new one is created on the next signing; retired keys stay in the JWKS for
15//! [`Jwt::grace_period`] (30 days) so tokens they signed keep verifying.
16//!
17//! ```
18//! use fastauth_core::prelude::*;
19//! use fastauth_plugin_jwt::{Jwt, JwtExt};
20//!
21//! # tokio_test(async {
22//! let auth: Auth<MemoryAdapter, (), plugins![Jwt]> = FastAuth::builder()
23//!     .secret(Secret::from_bytes(vec![1u8; 32]))
24//!     .base_url("https://acme.dk")
25//!     .database(MemoryAdapter::new())
26//!     .plugin(Jwt::new().expiration_time(Duration::minutes(5)))
27//!     .build()?;
28//!
29//! let token = auth
30//!     .jwt()
31//!     .sign(serde_json::json!({ "sub": "user_1" }).as_object().unwrap().clone())
32//!     .await?;
33//! let claims = auth.jwt().verify(&token).await?.expect("valid");
34//! assert_eq!(claims["sub"], "user_1");
35//! assert_eq!(claims["iss"], "https://acme.dk");
36//! # Ok::<(), Box<dyn std::error::Error>>(())
37//! # });
38//! # fn tokio_test<F: std::future::Future>(f: F) -> F::Output {
39//! #     tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(f)
40//! # }
41//! ```
42//!
43//! Resource servers verify tokens with [`verify::JwksVerifier`], built from the JWKS.
44
45mod endpoints;
46mod keys;
47mod model;
48pub mod verify;
49
50use std::future::Future;
51use std::pin::Pin;
52
53use fastauth_core::plugin_prelude::*;
54use fastauth_core::routes::GetSession;
55use http::header::ACCESS_CONTROL_EXPOSE_HEADERS;
56use http::{HeaderName, HeaderValue};
57use serde_json::{Map, Value};
58
59pub use endpoints::{
60    GetJwks, GetToken, Jwks, RotateKeys, RotatedKey, SignJwt, SignJwtInput, TokenOutput, VerifyJwt,
61    VerifyJwtInput, VerifyJwtOutput,
62};
63pub use jsonwebtoken;
64pub use model::JsonWebKey;
65pub use verify::{JwksVerifier, VerifyError};
66
67/// The response header `/get-session` carries the session's JWT in.
68pub const SET_AUTH_JWT: &str = "set-auth-jwt";
69
70/// The algorithm new keys use.
71#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
72pub enum JwtAlgorithm {
73    /// Ed25519, Better Auth's default.
74    #[default]
75    EdDSA,
76    /// ECDSA on P-256 with SHA-256.
77    ES256,
78    /// RSA PKCS#1 v1.5 with SHA-256, 2048-bit keys.
79    RS256,
80}
81
82impl JwtAlgorithm {
83    /// The JOSE name: `EdDSA`, `ES256`, `RS256`.
84    pub fn name(self) -> &'static str {
85        match self {
86            JwtAlgorithm::EdDSA => "EdDSA",
87            JwtAlgorithm::ES256 => "ES256",
88            JwtAlgorithm::RS256 => "RS256",
89        }
90    }
91}
92
93type Claims = Map<String, Value>;
94type DefinePayload = Arc<
95    dyn Fn(SessionView) -> Pin<Box<dyn Future<Output = Result<Claims, AuthError>> + Send>>
96        + Send
97        + Sync,
98>;
99
100/// The JWT plugin: `.plugin(Jwt::new())`.
101#[derive(Clone)]
102pub struct Jwt {
103    alg: JwtAlgorithm,
104    issuer: Option<String>,
105    audience: Option<String>,
106    expiration_time: Duration,
107    rotation_interval: Option<Duration>,
108    grace_period: Duration,
109    set_jwt_header: bool,
110    define_payload: Option<DefinePayload>,
111}
112
113impl std::fmt::Debug for Jwt {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        f.debug_struct("Jwt")
116            .field("alg", &self.alg)
117            .field("issuer", &self.issuer)
118            .field("audience", &self.audience)
119            .field("expiration_time", &self.expiration_time)
120            .field("rotation_interval", &self.rotation_interval)
121            .field("grace_period", &self.grace_period)
122            .finish_non_exhaustive()
123    }
124}
125
126impl Default for Jwt {
127    fn default() -> Self {
128        Self {
129            alg: JwtAlgorithm::EdDSA,
130            issuer: None,
131            audience: None,
132            expiration_time: Duration::minutes(15),
133            rotation_interval: None,
134            grace_period: Duration::days(30),
135            set_jwt_header: true,
136            define_payload: None,
137        }
138    }
139}
140
141impl Jwt {
142    pub fn new() -> Self {
143        Self::default()
144    }
145
146    /// The algorithm of new keys (default EdDSA). Switching mints a key of the new algorithm
147    /// on the next signing; tokens signed by the old keys keep verifying.
148    pub fn algorithm(mut self, alg: JwtAlgorithm) -> Self {
149        self.alg = alg;
150        self
151    }
152
153    /// The `iss` of every token (default: the base URL).
154    pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
155        self.issuer = Some(issuer.into());
156        self
157    }
158
159    /// The `aud` of every token (default: the base URL).
160    pub fn audience(mut self, audience: impl Into<String>) -> Self {
161        self.audience = Some(audience.into());
162        self
163    }
164
165    /// How long tokens are valid (default 15 minutes).
166    pub fn expiration_time(mut self, ttl: Duration) -> Self {
167        self.expiration_time = ttl;
168        self
169    }
170
171    /// Keys expire this long after they're created, and the next signing creates a new one
172    /// (default: keys never expire). Better Auth's `jwks.rotationInterval`.
173    pub fn rotation_interval(mut self, interval: Duration) -> Self {
174        self.rotation_interval = Some(interval);
175        self
176    }
177
178    /// How long an expired key stays in the JWKS (default 30 days). Keep it longer than
179    /// `expiration_time`. Better Auth's `jwks.gracePeriod`.
180    pub fn grace_period(mut self, grace: Duration) -> Self {
181        self.grace_period = grace;
182        self
183    }
184
185    /// Stops `/get-session` from signing a token into `set-auth-jwt` on every call. Better
186    /// Auth's `disableSettingJwtHeader`.
187    pub fn disable_jwt_header(mut self) -> Self {
188        self.set_jwt_header = false;
189        self
190    }
191
192    /// The claims a session's token carries instead of the user. `sub` is always the user id
193    /// and `iat`, `exp`, `iss` and `aud` are added unless the claims set them. Better
194    /// Auth's `jwt.definePayload`.
195    ///
196    /// ```
197    /// # use fastauth_plugin_jwt::Jwt;
198    /// let jwt = Jwt::new().define_payload(|session| async move {
199    ///     let mut claims = serde_json::Map::new();
200    ///     claims.insert("email".into(), session.user.email.clone().into());
201    ///     claims.insert("role".into(), "member".into());
202    ///     Ok(claims)
203    /// });
204    /// ```
205    pub fn define_payload<F, Fut>(mut self, define: F) -> Self
206    where
207        F: Fn(SessionView) -> Fut + Send + Sync + 'static,
208        Fut: Future<Output = Result<Map<String, Value>, AuthError>> + Send + 'static,
209    {
210        self.define_payload = Some(Arc::new(move |session| Box::pin(define(session))));
211        self
212    }
213}
214
215impl Plugin for Jwt {
216    const ID: &'static str = "jwt";
217    type Requires = ();
218    type UserFields = ();
219    type SessionFields = ();
220
221    fn schema(&self, schema: &mut SchemaBuilder) {
222        schema.model::<JsonWebKey>();
223    }
224
225    fn init<D: Adapter>(self: &Arc<Self>, app: &mut PluginBuilder<'_, D>) {
226        app.endpoint(GetJwks)
227            .endpoint(GetToken)
228            .server_endpoint::<SignJwt>()
229            .server_endpoint::<VerifyJwt>()
230            .server_endpoint::<RotateKeys>();
231        if self.set_jwt_header {
232            app.hook::<GetSession>().after(set_jwt_header);
233        }
234    }
235}
236
237async fn set_jwt_header<D: Adapter>(
238    ctx: HookCtx<D>,
239    output: Option<Value>,
240) -> Result<After<Option<Value>>, AuthError> {
241    if let Some(session) = ctx.session() {
242        let token = keys::session_token(&ctx, ctx.plugin::<Jwt>(), session).await?;
243        let value = HeaderValue::from_str(&token).map_err(AuthError::internal)?;
244        ctx.set_header(HeaderName::from_static(SET_AUTH_JWT), value);
245        ctx.set_header(
246            ACCESS_CONTROL_EXPOSE_HEADERS,
247            HeaderValue::from_static(SET_AUTH_JWT),
248        );
249    }
250    Ok(After::Continue(output))
251}
252
253/// `auth.jwt()`: the server API. Only compiles on an `Auth` with `Jwt` registered.
254pub trait JwtExt: AuthInstance + Sized {
255    fn jwt<I>(&self) -> JwtApi<'_, Self>
256    where
257        Self: HasPlugin<Jwt, I>,
258    {
259        JwtApi {
260            auth: self,
261            headers: HeaderMap::new(),
262        }
263    }
264}
265
266impl<A: AuthInstance> JwtExt for A {}
267
268/// Signs, verifies and rotates without HTTP.
269pub struct JwtApi<'a, A> {
270    auth: &'a A,
271    headers: HeaderMap,
272}
273
274impl<A> std::fmt::Debug for JwtApi<'_, A> {
275    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
276        f.write_str("JwtApi")
277    }
278}
279
280impl<A: AuthInstance> JwtApi<'_, A> {
281    /// Acts for the session in these request headers (for [`token`](Self::token)).
282    pub fn headers(mut self, headers: &HeaderMap) -> Self {
283        self.headers = headers.clone();
284        self
285    }
286
287    async fn call<E: Endpoint<A::Db>>(
288        &self,
289        endpoint: &E,
290        input: E::Input,
291    ) -> Result<E::Output, AuthError> {
292        Ok(self
293            .auth
294            .api()
295            .headers(&self.headers)
296            .call(endpoint, input)
297            .await?
298            .data)
299    }
300
301    /// The session's token, as `/token` answers it. Needs [`headers`](Self::headers) with
302    /// a session; `UNAUTHORIZED` without one.
303    pub async fn token(&self) -> Result<String, AuthError> {
304        Ok(self.call(&GetToken, Map::new()).await?.token)
305    }
306
307    /// Signs any claims with the current key. `exp`, `iss` and `aud` are added unless set.
308    pub async fn sign(&self, claims: Map<String, Value>) -> Result<String, AuthError> {
309        Ok(self
310            .call(&SignJwt, SignJwtInput { payload: claims })
311            .await?
312            .token)
313    }
314
315    /// The claims of a token signed by any stored key, with a valid `exp`, `iss` and
316    /// `aud`; `None` when it doesn't verify.
317    pub async fn verify(&self, token: &str) -> Result<Option<Map<String, Value>>, AuthError> {
318        let input = VerifyJwtInput {
319            token: token.to_owned(),
320            issuer: None,
321        };
322        Ok(self.call(&VerifyJwt, input).await?.payload)
323    }
324
325    /// The JWKS, as `/jwks` answers it.
326    pub async fn jwks(&self) -> Result<Jwks, AuthError> {
327        self.call(&GetJwks, Map::new()).await
328    }
329
330    /// Retires every live key and creates a new one, returning its `kid`. Tokens signed by
331    /// the retired keys verify until the grace period ends.
332    pub async fn rotate(&self) -> Result<Id, AuthError> {
333        Ok(self.call(&RotateKeys, Empty {}).await?.kid)
334    }
335}