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) => DecodingKey::from_base64_secret(&params.value),
187        }
188    }
189
190    pub(crate) fn as_bytes(&self) -> &[u8] {
191        match &self.kind {
192            DecodingKeyKind::SecretOrDer(b) => b,
193            DecodingKeyKind::RsaModulusExponent { .. } => unreachable!(),
194        }
195    }
196}
197
198/// Verify signature of a JWT, and return header object and raw payload
199///
200/// If the token or its signature is invalid, it will return an error.
201fn verify_signature<'a>(
202    token: &'a str,
203    key: &DecodingKey,
204    validation: &Validation,
205) -> Result<(Header, &'a str)> {
206    if validation.validate_signature && validation.algorithms.is_empty() {
207        return Err(new_error(ErrorKind::MissingAlgorithm));
208    }
209
210    if validation.validate_signature {
211        for alg in &validation.algorithms {
212            if key.family != alg.family() {
213                return Err(new_error(ErrorKind::InvalidAlgorithm));
214            }
215        }
216    }
217
218    let (signature, message) = expect_two!(token.rsplitn(2, '.'));
219    let (payload, header) = expect_two!(message.rsplitn(2, '.'));
220    let header = Header::from_encoded(header)?;
221
222    if validation.validate_signature && !validation.algorithms.contains(&header.alg) {
223        return Err(new_error(ErrorKind::InvalidAlgorithm));
224    }
225
226    if validation.validate_signature && !verify(signature, message.as_bytes(), key, header.alg)? {
227        return Err(new_error(ErrorKind::InvalidSignature));
228    }
229
230    Ok((header, payload))
231}
232
233/// Decode and validate a JWT
234///
235/// If the token or its signature is invalid or the claims fail validation, it will return an error.
236///
237/// ```rust
238/// use serde::{Deserialize, Serialize};
239/// use jsonwebtoken::{decode, DecodingKey, Validation, Algorithm};
240///
241/// #[derive(Debug, Serialize, Deserialize)]
242/// struct Claims {
243///    sub: String,
244///    company: String
245/// }
246///
247/// let token = "a.jwt.token".to_string();
248/// // Claims is a struct that implements Deserialize
249/// let token_message = decode::<Claims>(&token, &DecodingKey::from_secret("secret".as_ref()), &Validation::new(Algorithm::HS256));
250/// ```
251pub fn decode<T: DeserializeOwned>(
252    token: &str,
253    key: &DecodingKey,
254    validation: &Validation,
255) -> Result<TokenData<T>> {
256    match verify_signature(token, key, validation) {
257        Err(e) => Err(e),
258        Ok((header, claims)) => {
259            let decoded_claims = DecodedJwtPartClaims::from_jwt_part_claims(claims)?;
260            let claims = decoded_claims.deserialize()?;
261            validate(decoded_claims.deserialize()?, validation)?;
262
263            Ok(TokenData { header, claims })
264        }
265    }
266}
267
268/// Decode a JWT without any signature verification/validations and return its [Header](struct.Header.html).
269///
270/// If the token has an invalid format (ie 3 parts separated by a `.`), it will return an error.
271///
272/// ```rust
273/// use jsonwebtoken::decode_header;
274///
275/// let token = "a.jwt.token".to_string();
276/// let header = decode_header(&token);
277/// ```
278pub fn decode_header(token: &str) -> Result<Header> {
279    let (_, message) = expect_two!(token.rsplitn(2, '.'));
280    let (_, header) = expect_two!(message.rsplitn(2, '.'));
281    Header::from_encoded(header)
282}