jsonwebtoken/
decoding.rs

1use base64::{engine::general_purpose::STANDARD, Engine};
2use serde::de::DeserializeOwned;
3
4use crate::algorithms::AlgorithmFamily;
5use crate::crypto::verify;
6use crate::errors::{new_error, ErrorKind, Result};
7use crate::header::Header;
8use crate::jwk::{AlgorithmParameters, Jwk};
9#[cfg(feature = "use_pem")]
10use crate::pem::decoder::PemEncodedKey;
11use crate::serialization::{b64_decode, DecodedJwtPartClaims};
12use crate::validation::{validate, Validation};
13
14/// The return type of a successful call to [decode](fn.decode.html).
15#[derive(Debug)]
16pub struct TokenData<T> {
17    /// The decoded JWT header
18    pub header: Header,
19    /// The decoded JWT claims
20    pub claims: T,
21}
22
23impl<T> Clone for TokenData<T>
24where
25    T: Clone,
26{
27    fn clone(&self) -> Self {
28        Self { header: self.header.clone(), claims: self.claims.clone() }
29    }
30}
31
32/// Takes the result of a rsplit and ensure we only get 2 parts
33/// Errors if we don't
34macro_rules! expect_two {
35    ($iter:expr) => {{
36        let mut i = $iter;
37        match (i.next(), i.next(), i.next()) {
38            (Some(first), Some(second), None) => (first, second),
39            _ => return Err(new_error(ErrorKind::InvalidToken)),
40        }
41    }};
42}
43
44#[derive(Clone)]
45pub(crate) enum DecodingKeyKind {
46    SecretOrDer(Vec<u8>),
47    RsaModulusExponent { n: Vec<u8>, e: Vec<u8> },
48}
49
50/// All the different kind of keys we can use to decode a JWT.
51/// This key can be re-used so make sure you only initialize it once if you can for better performance.
52#[derive(Clone)]
53pub struct DecodingKey {
54    pub(crate) family: AlgorithmFamily,
55    pub(crate) kind: DecodingKeyKind,
56}
57
58impl DecodingKey {
59    /// If you're using HMAC, use this.
60    pub fn from_secret(secret: &[u8]) -> Self {
61        DecodingKey {
62            family: AlgorithmFamily::Hmac,
63            kind: DecodingKeyKind::SecretOrDer(secret.to_vec()),
64        }
65    }
66
67    /// If you're using HMAC with a base64 encoded secret, use this.
68    pub fn from_base64_secret(secret: &str) -> Result<Self> {
69        let out = STANDARD.decode(secret)?;
70        Ok(DecodingKey { family: AlgorithmFamily::Hmac, kind: DecodingKeyKind::SecretOrDer(out) })
71    }
72
73    /// If you are loading a public RSA key in a PEM format, use this.
74    /// Only exists if the feature `use_pem` is enabled.
75    #[cfg(feature = "use_pem")]
76    pub fn from_rsa_pem(key: &[u8]) -> Result<Self> {
77        let pem_key = PemEncodedKey::new(key)?;
78        let content = pem_key.as_rsa_key()?;
79        Ok(DecodingKey {
80            family: AlgorithmFamily::Rsa,
81            kind: DecodingKeyKind::SecretOrDer(content.to_vec()),
82        })
83    }
84
85    /// If you have (n, e) RSA public key components as strings, use this.
86    pub fn from_rsa_components(modulus: &str, exponent: &str) -> Result<Self> {
87        let n = b64_decode(modulus)?;
88        let e = b64_decode(exponent)?;
89        Ok(DecodingKey {
90            family: AlgorithmFamily::Rsa,
91            kind: DecodingKeyKind::RsaModulusExponent { n, e },
92        })
93    }
94
95    /// If you have (n, e) RSA public key components already decoded, use this.
96    pub fn from_rsa_raw_components(modulus: &[u8], exponent: &[u8]) -> Self {
97        DecodingKey {
98            family: AlgorithmFamily::Rsa,
99            kind: DecodingKeyKind::RsaModulusExponent { n: modulus.to_vec(), e: exponent.to_vec() },
100        }
101    }
102
103    /// If you have a ECDSA public key in PEM format, use this.
104    /// Only exists if the feature `use_pem` is enabled.
105    #[cfg(feature = "use_pem")]
106    pub fn from_ec_pem(key: &[u8]) -> Result<Self> {
107        let pem_key = PemEncodedKey::new(key)?;
108        let content = pem_key.as_ec_public_key()?;
109        Ok(DecodingKey {
110            family: AlgorithmFamily::Ec,
111            kind: DecodingKeyKind::SecretOrDer(content.to_vec()),
112        })
113    }
114
115    /// If you have (x,y) ECDSA key components
116    pub fn from_ec_components(x: &str, y: &str) -> Result<Self> {
117        let x_cmp = b64_decode(x)?;
118        let y_cmp = b64_decode(y)?;
119
120        let mut public_key = Vec::with_capacity(1 + x.len() + y.len());
121        public_key.push(0x04);
122        public_key.extend_from_slice(&x_cmp);
123        public_key.extend_from_slice(&y_cmp);
124
125        Ok(DecodingKey {
126            family: AlgorithmFamily::Ec,
127            kind: DecodingKeyKind::SecretOrDer(public_key),
128        })
129    }
130
131    /// If you have a EdDSA public key in PEM format, use this.
132    /// Only exists if the feature `use_pem` is enabled.
133    #[cfg(feature = "use_pem")]
134    pub fn from_ed_pem(key: &[u8]) -> Result<Self> {
135        let pem_key = PemEncodedKey::new(key)?;
136        let content = pem_key.as_ed_public_key()?;
137        Ok(DecodingKey {
138            family: AlgorithmFamily::Ed,
139            kind: DecodingKeyKind::SecretOrDer(content.to_vec()),
140        })
141    }
142
143    /// If you know what you're doing and have a RSA DER encoded public key, use this.
144    pub fn from_rsa_der(der: &[u8]) -> Self {
145        DecodingKey {
146            family: AlgorithmFamily::Rsa,
147            kind: DecodingKeyKind::SecretOrDer(der.to_vec()),
148        }
149    }
150
151    /// If you know what you're doing and have a RSA EC encoded public key, use this.
152    pub fn from_ec_der(der: &[u8]) -> Self {
153        DecodingKey {
154            family: AlgorithmFamily::Ec,
155            kind: DecodingKeyKind::SecretOrDer(der.to_vec()),
156        }
157    }
158
159    /// If you know what you're doing and have a Ed DER encoded public key, use this.
160    pub fn from_ed_der(der: &[u8]) -> Self {
161        DecodingKey {
162            family: AlgorithmFamily::Ed,
163            kind: DecodingKeyKind::SecretOrDer(der.to_vec()),
164        }
165    }
166
167    /// From x part (base64 encoded) of the JWK encoding
168    pub fn from_ed_components(x: &str) -> Result<Self> {
169        let x_decoded = b64_decode(x)?;
170        Ok(DecodingKey {
171            family: AlgorithmFamily::Ed,
172            kind: DecodingKeyKind::SecretOrDer(x_decoded),
173        })
174    }
175
176    /// If you have a key in Jwk format
177    pub fn from_jwk(jwk: &Jwk) -> Result<Self> {
178        match &jwk.algorithm {
179            AlgorithmParameters::RSA(params) => {
180                DecodingKey::from_rsa_components(&params.n, &params.e)
181            }
182            AlgorithmParameters::EllipticCurve(params) => {
183                DecodingKey::from_ec_components(&params.x, &params.y)
184            }
185            AlgorithmParameters::OctetKeyPair(params) => DecodingKey::from_ed_components(&params.x),
186            AlgorithmParameters::OctetKey(params) => {
187                let out = b64_decode(&params.value)?;
188                Ok(DecodingKey {
189                    family: AlgorithmFamily::Hmac,
190                    kind: DecodingKeyKind::SecretOrDer(out),
191                })
192            }
193        }
194    }
195
196    pub(crate) fn as_bytes(&self) -> &[u8] {
197        match &self.kind {
198            DecodingKeyKind::SecretOrDer(b) => b,
199            DecodingKeyKind::RsaModulusExponent { .. } => unreachable!(),
200        }
201    }
202}
203
204/// Verify signature of a JWT, and return header object and raw payload
205///
206/// If the token or its signature is invalid, it will return an error.
207fn verify_signature<'a>(
208    token: &'a str,
209    key: &DecodingKey,
210    validation: &Validation,
211) -> Result<(Header, &'a str)> {
212    if validation.validate_signature && validation.algorithms.is_empty() {
213        return Err(new_error(ErrorKind::MissingAlgorithm));
214    }
215
216    if validation.validate_signature {
217        for alg in &validation.algorithms {
218            if key.family != alg.family() {
219                return Err(new_error(ErrorKind::InvalidAlgorithm));
220            }
221        }
222    }
223
224    let (signature, message) = expect_two!(token.rsplitn(2, '.'));
225    let (payload, header) = expect_two!(message.rsplitn(2, '.'));
226    let header = Header::from_encoded(header)?;
227
228    if validation.validate_signature && !validation.algorithms.contains(&header.alg) {
229        return Err(new_error(ErrorKind::InvalidAlgorithm));
230    }
231
232    if validation.validate_signature && !verify(signature, message.as_bytes(), key, header.alg)? {
233        return Err(new_error(ErrorKind::InvalidSignature));
234    }
235
236    Ok((header, payload))
237}
238
239/// Decode and validate a JWT
240///
241/// If the token or its signature is invalid or the claims fail validation, it will return an error.
242///
243/// ```rust
244/// use serde::{Deserialize, Serialize};
245/// use jsonwebtoken::{decode, DecodingKey, Validation, Algorithm};
246///
247/// #[derive(Debug, Serialize, Deserialize)]
248/// struct Claims {
249///    sub: String,
250///    company: String
251/// }
252///
253/// let token = "a.jwt.token".to_string();
254/// // Claims is a struct that implements Deserialize
255/// let token_message = decode::<Claims>(&token, &DecodingKey::from_secret("secret".as_ref()), &Validation::new(Algorithm::HS256));
256/// ```
257pub fn decode<T: DeserializeOwned>(
258    token: &str,
259    key: &DecodingKey,
260    validation: &Validation,
261) -> Result<TokenData<T>> {
262    match verify_signature(token, key, validation) {
263        Err(e) => Err(e),
264        Ok((header, claims)) => {
265            let decoded_claims = DecodedJwtPartClaims::from_jwt_part_claims(claims)?;
266            let claims = decoded_claims.deserialize()?;
267            validate(decoded_claims.deserialize()?, validation)?;
268
269            Ok(TokenData { header, claims })
270        }
271    }
272}
273
274/// Decode a JWT without any signature verification/validations and return its [Header](struct.Header.html).
275///
276/// If the token has an invalid format (ie 3 parts separated by a `.`), it will return an error.
277///
278/// ```rust
279/// use jsonwebtoken::decode_header;
280///
281/// let token = "a.jwt.token".to_string();
282/// let header = decode_header(&token);
283/// ```
284pub fn decode_header(token: &str) -> Result<Header> {
285    let (_, message) = expect_two!(token.rsplitn(2, '.'));
286    let (_, header) = expect_two!(message.rsplitn(2, '.'));
287    Header::from_encoded(header)
288}