jsonwebtoken/
serialization.rs

1use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
2use serde::{Deserialize, Serialize};
3
4use crate::errors::Result;
5
6pub(crate) fn b64_encode<T: AsRef<[u8]>>(input: T) -> String {
7    URL_SAFE_NO_PAD.encode(input)
8}
9
10pub(crate) fn b64_decode<T: AsRef<[u8]>>(input: T) -> Result<Vec<u8>> {
11    URL_SAFE_NO_PAD.decode(input).map_err(|e| e.into())
12}
13
14/// Serializes a struct to JSON and encodes it in base64
15pub(crate) fn b64_encode_part<T: Serialize>(input: &T) -> Result<String> {
16    let json = serde_json::to_vec(input)?;
17    Ok(b64_encode(json))
18}
19
20/// This is used to decode from base64 then deserialize from JSON to several structs:
21/// - The user-provided struct
22/// - The ClaimsForValidation struct from this crate to run validation on
23pub(crate) struct DecodedJwtPartClaims {
24    b64_decoded: Vec<u8>,
25}
26
27impl DecodedJwtPartClaims {
28    pub fn from_jwt_part_claims(encoded_jwt_part_claims: impl AsRef<[u8]>) -> Result<Self> {
29        Ok(Self { b64_decoded: b64_decode(encoded_jwt_part_claims)? })
30    }
31
32    pub fn deserialize<'a, T: Deserialize<'a>>(&'a self) -> Result<T> {
33        Ok(serde_json::from_slice(&self.b64_decoded)?)
34    }
35}