jsonwebtoken/src/serialization.rs

41 lines
1.2 KiB
Rust
Raw Normal View History

2017-02-22 02:45:28 -05:00
use base64;
use serde::de::Deserialize;
use serde::ser::Serialize;
2017-04-11 01:41:44 -04:00
use serde_json::{from_str, to_string, Value};
use serde_json::map::Map;
2017-02-22 02:45:28 -05:00
use errors::{Result};
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)]
pub struct TokenData<T: Deserialize> {
pub header: Header,
pub claims: T
}
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
2017-02-22 02:45:28 -05:00
pub fn from_jwt_part<B: AsRef<str>, T: Deserialize>(encoded: B) -> Result<T> {
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
pub fn from_jwt_part_claims<B: AsRef<str>, T: Deserialize>(encoded: B) -> Result<(T, Map<String, Value>)> {
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)?;
let map: Map<_,_> = from_str(&s)?;
Ok((claims, map))
2017-02-22 02:45:28 -05:00
}