1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
//! Allow to create own session extractor and extract from cookie or header.

use crate::*;

/// Trait allowing to extract JWt token from [actix_web::dev::ServiceRequest]
///
/// Two extractor are implemented by default
/// * [HeaderExtractor] which is best for any PWA or micro services requests
/// * [CookieExtractor] which is best for simple server with session stored in cookie
///
/// It's possible to implement GraphQL, JSON payload or query using `req.extract::<JSON<YourStruct>>()` if this is needed.
///
/// All implementation can use [SessionExtractor::decode] method for decoding raw JWT string into
/// Claims and then [SessionExtractor::validate] to validate claims agains session stored in [SessionStorage]
#[async_trait(?Send)]
pub trait SessionExtractor<ClaimsType: Claims>: Send + Sync + 'static {
    /// Extract claims from [actix_web::dev::ServiceRequest]
    ///
    /// Examples:
    ///
    /// ```
    /// use actix_web::dev::ServiceRequest;
    /// use jsonwebtoken::*;
    /// use actix_jwt_session::*;
    /// use std::sync::Arc;
    /// use actix_web::HttpMessage;
    /// use std::borrow::Cow;
    ///
    /// # #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
    /// # pub struct Claims { id: uuid::Uuid, sub: String }
    /// # impl actix_jwt_session::Claims for Claims {
    /// #     fn jti(&self) -> uuid::Uuid { self.id }
    /// #     fn subject(&self) -> &str { &self.sub }
    /// # }
    ///
    /// #[derive(Debug, Clone, Copy, Default)]
    /// struct ExampleExtractor;
    ///
    /// #[async_trait::async_trait(?Send)]
    /// impl SessionExtractor<Claims> for ExampleExtractor {
    ///     async fn extract_claims(
    ///         &self,
    ///         req: &mut ServiceRequest,
    ///         jwt_encoding_key: Arc<EncodingKey>,
    ///         jwt_decoding_key: Arc<DecodingKey>,
    ///         algorithm: Algorithm,
    ///         storage: SessionStorage,
    ///     ) -> Result<(), Error> {
    ///         if req.peer_addr().unwrap().ip().is_multicast() {
    ///            req.extensions_mut().insert(Authenticated {
    ///                claims: Arc::new(Claims { id: uuid::Uuid::default(), sub: "HUB".into() }),
    ///                jwt_encoding_key,
    ///                algorithm,
    ///            });
    ///         }
    ///         Ok(())
    ///     }
    ///
    ///     async fn extract_token_text<'req>(&self, req: &'req mut ServiceRequest) -> Option<Cow<'req, str>> { None }
    /// }
    /// ```
    async fn extract_claims(
        &self,
        req: &mut ServiceRequest,
        jwt_encoding_key: Arc<EncodingKey>,
        jwt_decoding_key: Arc<DecodingKey>,
        algorithm: Algorithm,
        storage: SessionStorage,
    ) -> Result<(), Error> {
        let Some(as_str) = self.extract_token_text(req).await else {
            return Ok(());
        };
        let decoded_claims = self.decode(&as_str, jwt_decoding_key, algorithm)?;
        self.validate(&decoded_claims, storage).await?;
        req.extensions_mut().insert(Authenticated {
            claims: Arc::new(decoded_claims),
            jwt_encoding_key,
            algorithm,
        });
        Ok(())
    }

    /// Decode encrypted JWT to structure
    fn decode(
        &self,
        value: &str,
        jwt_decoding_key: Arc<DecodingKey>,
        algorithm: Algorithm,
    ) -> Result<ClaimsType, Error> {
        let mut validation = Validation::new(algorithm);
        validation.validate_exp = false;
        validation.validate_nbf = false;
        validation.leeway = 0;
        validation.required_spec_claims.clear();

        decode::<ClaimsType>(value, &jwt_decoding_key, &validation)
            .map_err(|e| {
                #[cfg(feature = "use-tracing")]
                tracing::debug!("Failed to decode claims: {e:?}. {e}");
                Error::CantDecode
            })
            .map(|t| t.claims)
    }

    /// Validate JWT Claims agains stored in storage tokens.
    ///
    /// * Token must exists in storage
    /// * Token must be exactly the same as token from storage
    async fn validate(&self, claims: &ClaimsType, storage: SessionStorage) -> Result<(), Error> {
        let stored = storage
            .clone()
            .find_jwt::<ClaimsType>(claims.jti())
            .await
            .map_err(|e| {
                #[cfg(feature = "use-tracing")]
                tracing::debug!(
                    "Failed to load {} from storage: {e:?}",
                    std::any::type_name::<ClaimsType>()
                );
                Error::LoadError
            })?;

        if &stored != claims {
            #[cfg(feature = "use-tracing")]
            tracing::debug!("{claims:?} != {stored:?}");
            Err(Error::DontMatch)
        } else {
            Ok(())
        }
    }

    /// Lookup for session data as a string in [actix_web::dev::ServiceRequest]
    ///
    /// If there's no token data in request you should returns `None`. This is not considered as an
    /// error and until endpoint requires `Authenticated` this will not results in `401`.
    async fn extract_token_text<'req>(
        &self,
        req: &'req mut ServiceRequest,
    ) -> Option<Cow<'req, str>>;
}

/// Extracts JWT token from HTTP Request cookies. This extractor should be used when you can't set
/// your own header, for example when user enters http links to browser and you don't have any
/// advanced frontend.
///
/// This exractor is may be used by PWA application or micro services but [HeaderExtractor] is much
/// more suitable for this purpose.
pub struct CookieExtractor<ClaimsType> {
    __ty: PhantomData<ClaimsType>,
    cookie_name: &'static str,
}

impl<ClaimsType: Claims> CookieExtractor<ClaimsType> {
    /// Creates new cookie extractor.
    /// It will extract token data from cookie with given name
    pub fn new(cookie_name: &'static str) -> Self {
        Self {
            __ty: Default::default(),
            cookie_name,
        }
    }
}

#[async_trait(?Send)]
impl<ClaimsType: Claims> SessionExtractor<ClaimsType> for CookieExtractor<ClaimsType> {
    async fn extract_token_text<'req>(
        &self,
        req: &'req mut ServiceRequest,
    ) -> Option<Cow<'req, str>> {
        req.cookie(self.cookie_name)
            .map(|c| c.value().to_string().into())
    }
}

/// Extracts JWT token from HTTP Request headers
///
/// This exractor is very useful for all PWA application or for micro services
/// because you can set your own headers while making http requests.
///
/// If you want to have users authorized using simple html anchor (tag A) you should use [CookieExtractor]
pub struct HeaderExtractor<ClaimsType> {
    __ty: PhantomData<ClaimsType>,
    header_name: &'static str,
}

impl<ClaimsType: Claims> HeaderExtractor<ClaimsType> {
    /// Creates new header extractor.
    /// It will extract token data from header with given name
    pub fn new(header_name: &'static str) -> Self {
        Self {
            __ty: Default::default(),
            header_name,
        }
    }
}

#[async_trait(?Send)]
impl<ClaimsType: Claims> SessionExtractor<ClaimsType> for HeaderExtractor<ClaimsType> {
    async fn extract_token_text<'req>(
        &self,
        req: &'req mut ServiceRequest,
    ) -> Option<Cow<'req, str>> {
        req.headers()
            .get(self.header_name)
            .and_then(|h| h.to_str().ok())
            .map(|h| h.to_owned().into())
    }
}

pub struct JsonExtractor<ClaimsType> {
    __ty: PhantomData<ClaimsType>,
    // Path to field in JSON body
    path: &'static [&'static str],
}

impl<ClaimsType: Claims> JsonExtractor<ClaimsType> {
    /// Creates new json extractor.
    /// It will extract token data from json with given path inside
    ///
    /// NOTE: Arrays are not supported, only objects
    ///
    /// # Examples:
    ///
    /// ```rust
    /// use actix_jwt_session::{JsonExtractor, Claims};
    ///
    /// async fn create_extractor<C: Claims>() -> JsonExtractor<C> {
    ///     JsonExtractor::<C>::new(&["refresh_token"])
    /// }
    /// ```
    pub fn new(path: &'static [&'static str]) -> Self {
        Self {
            __ty: Default::default(),
            path,
        }
    }
}

#[async_trait(?Send)]
impl<ClaimsType: Claims> SessionExtractor<ClaimsType> for JsonExtractor<ClaimsType> {
    async fn extract_token_text<'req>(
        &self,
        req: &'req mut ServiceRequest,
    ) -> Option<Cow<'req, str>> {
        let Ok(v) = req
            .extract::<actix_web::web::Json<serde_json::Value>>()
            .await
        else {
            return None;
        };
        let json = v.into_inner();
        let mut v = &json;

        let len = self.path.len();
        self.path.iter().enumerate().fold(None, |_, (idx, piece)| {
            if idx + 1 == len {
                v.as_object()?
                    .get(*piece)?
                    .as_str()
                    .map(ToOwned::to_owned)
                    .map(Into::into)
            } else {
                v = v.as_object()?.get(*piece)?;
                None
            }
        })
    }
}