Skip to main content

fastauth_plugin_jwt/
endpoints.rs

1//! The JWT endpoints.
2
3use fastauth_core::plugin_prelude::*;
4use jsonwebtoken::jwk::JwkSet;
5use serde_json::{Map, Value};
6
7use crate::verify::JwksVerifier;
8use crate::{Jwt, keys};
9
10/// The body of `/jwks`.
11#[derive(Clone, Debug, Default, Serialize, Deserialize)]
12pub struct Jwks {
13    pub keys: Vec<Map<String, Value>>,
14}
15
16/// `GET /jwks`: the public keys, as Better Auth lists them. Creates the first key on first
17/// use.
18#[derive(Clone, Copy, Debug, Default)]
19pub struct GetJwks;
20
21impl<D: Adapter> Endpoint<D> for GetJwks {
22    const METHOD: Method = Method::GET;
23    const PATH: &'static str = "/jwks";
24    type Access = Public;
25    type Input = Map<String, Value>;
26    type Output = Jwks;
27
28    async fn call(&self, ctx: Ctx<D>, _: Map<String, Value>) -> Result<Jwks, AuthError> {
29        let jwt = ctx.plugin::<Jwt>();
30        keys::current(&ctx, jwt).await?;
31        let all = keys::all(&ctx).await?;
32        let keys = keys::published(&all, jwt, ctx.now())
33            .into_iter()
34            .map(|key| keys::public_jwk(key, jwt))
35            .collect::<Result<_, _>>()?;
36        Ok(Jwks { keys })
37    }
38}
39
40/// A signed token.
41#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
42pub struct TokenOutput {
43    pub token: String,
44}
45
46/// `GET /token`: a JWT for the request's session.
47#[derive(Clone, Copy, Debug, Default)]
48pub struct GetToken;
49
50impl<D: Adapter> Endpoint<D> for GetToken {
51    const METHOD: Method = Method::GET;
52    const PATH: &'static str = "/token";
53    type Access = Authenticated;
54    type Input = Map<String, Value>;
55    type Output = TokenOutput;
56
57    async fn call(
58        &self,
59        ctx: Ctx<D, Authenticated>,
60        _: Map<String, Value>,
61    ) -> Result<TokenOutput, AuthError> {
62        let token = keys::session_token(&ctx, ctx.plugin::<Jwt>(), ctx.session()).await?;
63        Ok(TokenOutput { token })
64    }
65}
66
67/// The input of [`SignJwt`].
68#[derive(Clone, Debug, Default, Serialize, Deserialize)]
69pub struct SignJwtInput {
70    pub payload: Map<String, Value>,
71}
72
73/// Server-only, like Better Auth's `signJWT`: signs any claims with the current key.
74#[derive(Clone, Copy, Debug, Default)]
75pub struct SignJwt;
76
77impl<D: Adapter> Endpoint<D> for SignJwt {
78    const METHOD: Method = Method::POST;
79    const PATH: &'static str = "/sign-jwt";
80    type Access = Public;
81    type Input = SignJwtInput;
82    type Output = TokenOutput;
83
84    async fn call(&self, ctx: Ctx<D>, input: SignJwtInput) -> Result<TokenOutput, AuthError> {
85        let token = keys::sign(&ctx, ctx.plugin::<Jwt>(), input.payload).await?;
86        Ok(TokenOutput { token })
87    }
88}
89
90/// The input of [`VerifyJwt`].
91#[derive(Clone, Debug, Default, Serialize, Deserialize)]
92pub struct VerifyJwtInput {
93    pub token: String,
94    /// Expected `iss`, instead of the configured issuer.
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub issuer: Option<String>,
97}
98
99/// What [`VerifyJwt`] answers: the claims, or `None` when the token doesn't verify.
100#[derive(Clone, Debug, Default, Serialize, Deserialize)]
101pub struct VerifyJwtOutput {
102    pub payload: Option<Map<String, Value>>,
103}
104
105/// Server-only, like Better Auth's `verifyJWT`: checks a token against every stored key.
106#[derive(Clone, Copy, Debug, Default)]
107pub struct VerifyJwt;
108
109impl<D: Adapter> Endpoint<D> for VerifyJwt {
110    const METHOD: Method = Method::POST;
111    const PATH: &'static str = "/verify-jwt";
112    type Access = Public;
113    type Input = VerifyJwtInput;
114    type Output = VerifyJwtOutput;
115
116    async fn call(&self, ctx: Ctx<D>, input: VerifyJwtInput) -> Result<VerifyJwtOutput, AuthError> {
117        let jwt = ctx.plugin::<Jwt>();
118        let keys = keys::all(&ctx)
119            .await?
120            .iter()
121            .map(|key| keys::public_jwk(key, jwt))
122            .collect::<Result<Vec<_>, _>>()?;
123        let jwks: JwkSet = serde_json::from_value(serde_json::json!({ "keys": keys }))
124            .map_err(AuthError::internal)?;
125        let base_url = ctx
126            .config()
127            .base_url
128            .as_str()
129            .trim_end_matches('/')
130            .to_owned();
131        let issuer = input
132            .issuer
133            .or_else(|| jwt.issuer.clone())
134            .unwrap_or_else(|| base_url.clone());
135        let audience = jwt.audience.clone().unwrap_or(base_url);
136        let payload = JwksVerifier::new(jwks, issuer, audience)
137            .verify(&input.token)
138            .ok();
139        Ok(VerifyJwtOutput { payload })
140    }
141}
142
143/// The key [`RotateKeys`] created.
144#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
145pub struct RotatedKey {
146    pub kid: Id,
147}
148
149/// Server-only: retires every live key (they keep verifying for the grace period) and
150/// creates a new one that signs from now on.
151#[derive(Clone, Copy, Debug, Default)]
152pub struct RotateKeys;
153
154impl<D: Adapter> Endpoint<D> for RotateKeys {
155    const METHOD: Method = Method::POST;
156    const PATH: &'static str = "/jwks/rotate";
157    type Access = Public;
158    type Input = Empty;
159    type Output = RotatedKey;
160
161    async fn call(&self, ctx: Ctx<D>, _: Empty) -> Result<RotatedKey, AuthError> {
162        let key = keys::rotate(&ctx, ctx.plugin::<Jwt>()).await?;
163        Ok(RotatedKey { kid: key.id })
164    }
165}