jsonwebtoken/header.rs
1use serde::{Deserialize, Serialize};
2
3use crate::algorithms::Algorithm;
4use crate::errors::Result;
5use crate::serialization::b64_decode;
6
7/// A basic JWT header, the alg defaults to HS256 and typ is automatically
8/// set to `JWT`. All the other fields are optional.
9#[derive(Debug, Clone, PartialEq, Hash, Serialize, Deserialize)]
10pub struct Header {
11 /// The type of JWS: it can only be "JWT" here
12 ///
13 /// Defined in [RFC7515#4.1.9](https://tools.ietf.org/html/rfc7515#section-4.1.9).
14 #[serde(skip_serializing_if = "Option::is_none")]
15 pub typ: Option<String>,
16 /// The algorithm used
17 ///
18 /// Defined in [RFC7515#4.1.1](https://tools.ietf.org/html/rfc7515#section-4.1.1).
19 pub alg: Algorithm,
20 /// Content type
21 ///
22 /// Defined in [RFC7519#5.2](https://tools.ietf.org/html/rfc7519#section-5.2).
23 #[serde(skip_serializing_if = "Option::is_none")]
24 pub cty: Option<String>,
25 /// JSON Key URL
26 ///
27 /// Defined in [RFC7515#4.1.2](https://tools.ietf.org/html/rfc7515#section-4.1.2).
28 #[serde(skip_serializing_if = "Option::is_none")]
29 pub jku: Option<String>,
30 /// Key ID
31 ///
32 /// Defined in [RFC7515#4.1.4](https://tools.ietf.org/html/rfc7515#section-4.1.4).
33 #[serde(skip_serializing_if = "Option::is_none")]
34 pub kid: Option<String>,
35 /// X.509 URL
36 ///
37 /// Defined in [RFC7515#4.1.5](https://tools.ietf.org/html/rfc7515#section-4.1.5).
38 #[serde(skip_serializing_if = "Option::is_none")]
39 pub x5u: Option<String>,
40 /// X.509 certificate thumbprint
41 ///
42 /// Defined in [RFC7515#4.1.7](https://tools.ietf.org/html/rfc7515#section-4.1.7).
43 #[serde(skip_serializing_if = "Option::is_none")]
44 pub x5t: Option<String>,
45}
46
47impl Header {
48 /// Returns a JWT header with the algorithm given
49 pub fn new(algorithm: Algorithm) -> Self {
50 Header {
51 typ: Some("JWT".to_string()),
52 alg: algorithm,
53 cty: None,
54 jku: None,
55 kid: None,
56 x5u: None,
57 x5t: None,
58 }
59 }
60
61 /// Converts an encoded part into the Header struct if possible
62 pub(crate) fn from_encoded(encoded_part: &str) -> Result<Self> {
63 let decoded = b64_decode(encoded_part)?;
64 let s = String::from_utf8(decoded)?;
65
66 Ok(serde_json::from_str(&s)?)
67 }
68}
69
70impl Default for Header {
71 /// Returns a JWT header using the default Algorithm, HS256
72 fn default() -> Self {
73 Header::new(Algorithm::default())
74 }
75}