Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/decoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,33 @@ pub fn decode_header(token: impl AsRef<[u8]>) -> Result<Header> {
Header::from_encoded(header)
}

/// Decode a JWT without any signature verification/validations and return its header as a custom type.
///
/// If the token has an invalid format (ie 3 parts separated by a `.`), it will return an error.
///
/// ```rust
/// use jsonwebtoken::decode_header_as;
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct MyHeader {
/// iss: String,
/// }
///
/// let token = "a.jwt.token".to_string();
/// let header: Result<MyHeader, _> = decode_header_as(&token);
/// ```
pub fn decode_header_as<T>(token: impl AsRef<[u8]>) -> Result<T>
where
T: DeserializeOwned,
{
let token = token.as_ref();
let (_, message) = expect_two!(token.rsplitn(2, |b| *b == b'.'));
let (_, header) = expect_two!(message.rsplitn(2, |b| *b == b'.'));
let decoded = b64_decode(header)?;
Ok(serde_json::from_slice(&decoded)?)
}

pub(crate) fn verify_signature_body(
message: &[u8],
signature: &[u8],
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ compile_error!(
compile_error!("at least one of the features \"rust_crypto\" or \"aws_lc_rs\" must be enabled");

pub use algorithms::Algorithm;
pub use decoding::{DecodingKey, TokenData, decode, decode_header};
pub use decoding::{DecodingKey, TokenData, decode, decode_header, decode_header_as};
pub use encoding::{EncodingKey, encode};
pub use header::Header;
pub use validation::{Validation, get_current_timestamp};
Expand Down