jwt_lab/decode.rs
1use crate::{b64, types::{Header, Claims, Jwt}, Error, Result};
2
3/// Decode a JWT token into its components
4///
5/// # Arguments
6///
7/// * `token` - The JWT token string to decode
8///
9/// # Returns
10///
11/// Returns a `Result` containing the decoded JWT or an error if the token is malformed
12///
13/// # Errors
14///
15/// - `Error::Malformed` if the token doesn't have exactly 3 parts separated by dots
16/// - `Error::Base64` if base64url decoding fails
17/// - `Error::Json` if JSON parsing of header or payload fails
18pub fn decode(token: &str) -> Result<Jwt> {
19 let parts: Vec<&str> = token.split('.').collect();
20 if parts.len() != 3 { return Err(Error::Malformed); }
21 let header: Header = serde_json::from_slice(&b64::decode_url(parts[0])?)
22 .map_err(|e| Error::Json(e.to_string()))?;
23 let claims_map: serde_json::Map<String, serde_json::Value> =
24 serde_json::from_slice(&b64::decode_url(parts[1])?).map_err(|e| Error::Json(e.to_string()))?;
25 Ok(Jwt {
26 header,
27 claims: Claims(claims_map),
28 signature_b64: parts[2].to_string(),
29 raw_header_b64: parts[0].to_string(),
30 raw_payload_b64: parts[1].to_string(),
31 })
32}
33
34impl crate::types::Jwt {
35 /// Decode a JWT token into its components
36 ///
37 /// This is a convenience method that calls the `decode` function.
38 ///
39 /// # Arguments
40 ///
41 /// * `token` - The JWT token string to decode
42 ///
43 /// # Returns
44 ///
45 /// Returns a `Result` containing the decoded JWT or an error if the token is malformed
46 pub fn decode(token: &str) -> Result<Self> { decode(token) }
47}