jsonwebtoken/src/serialization.rs

44 lines
1.3 KiB
Rust
Raw Normal View History

2017-02-22 02:45:28 -05:00
use base64;
use serde::de::DeserializeOwned;
2017-02-22 02:45:28 -05:00
use serde::ser::Serialize;
2017-04-11 01:41:44 -04:00
use serde_json::map::Map;
2018-10-28 14:58:35 -04:00
use serde_json::{from_str, to_string, Value};
2017-02-22 02:45:28 -05:00
2018-10-28 14:58:35 -04:00
use errors::Result;
2017-02-22 02:45:28 -05:00
use header::Header;
2017-04-12 21:08:07 -04:00
/// The return type of a successful call to decode
2017-02-22 02:45:28 -05:00
#[derive(Debug)]
2017-04-22 01:41:25 -04:00
pub struct TokenData<T> {
2017-07-02 17:49:14 -04:00
/// The decoded JWT header
2017-02-22 02:45:28 -05:00
pub header: Header,
2017-07-02 17:49:14 -04:00
/// The decoded JWT claims
2018-10-28 14:58:35 -04:00
pub claims: T,
2017-02-22 02:45:28 -05:00
}
2017-04-10 23:54:32 -04:00
/// Serializes to JSON and encodes to base64
2017-02-22 02:45:28 -05:00
pub fn to_jwt_part<T: Serialize>(input: &T) -> Result<String> {
2017-04-11 01:41:44 -04:00
let encoded = to_string(input)?;
2017-02-22 02:45:28 -05:00
Ok(base64::encode_config(encoded.as_bytes(), base64::URL_SAFE_NO_PAD))
}
2017-04-11 01:41:44 -04:00
/// Decodes from base64 and deserializes from JSON to a struct
pub fn from_jwt_part<B: AsRef<str>, T: DeserializeOwned>(encoded: B) -> Result<T> {
2017-02-22 02:45:28 -05:00
let decoded = base64::decode_config(encoded.as_ref(), base64::URL_SAFE_NO_PAD)?;
let s = String::from_utf8(decoded)?;
2017-04-11 01:41:44 -04:00
Ok(from_str(&s)?)
}
/// Decodes from base64 and deserializes from JSON to a struct AND a hashmap
2018-10-28 14:58:35 -04:00
pub fn from_jwt_part_claims<B: AsRef<str>, T: DeserializeOwned>(
encoded: B,
) -> Result<(T, Map<String, Value>)> {
2017-04-11 01:41:44 -04:00
let decoded = base64::decode_config(encoded.as_ref(), base64::URL_SAFE_NO_PAD)?;
let s = String::from_utf8(decoded)?;
let claims: T = from_str(&s)?;
2018-10-28 14:58:35 -04:00
let map: Map<_, _> = from_str(&s)?;
2017-04-11 01:41:44 -04:00
Ok((claims, map))
2017-02-22 02:45:28 -05:00
}