Encode the header and claims given and sign the payload using the algorithm from the header and the key. If the algorithm given is RSA or EC, the key needs to be in the PEM format. This produces a JWS instead of a JWT -- usage is similar to `encode`, see that for more details.
(
header: &Header,
claims: Option<&T>,
key: &EncodingKey,
)
| 35 | /// If the algorithm given is RSA or EC, the key needs to be in the PEM format. This produces a JWS instead of |
| 36 | /// a JWT -- usage is similar to `encode`, see that for more details. |
| 37 | pub fn encode<T: Serialize>( |
| 38 | header: &Header, |
| 39 | claims: Option<&T>, |
| 40 | key: &EncodingKey, |
| 41 | ) -> Result<Jws<T>> { |
| 42 | if key.family() != header.alg.family() { |
| 43 | return Err(new_error(ErrorKind::InvalidAlgorithm)); |
| 44 | } |
| 45 | let encoded_header = b64_encode_part(header)?; |
| 46 | let encoded_claims = match claims { |
| 47 | Some(claims) => b64_encode_part(claims)?, |
| 48 | None => "".to_string(), |
| 49 | }; |
| 50 | let message = [encoded_header.as_str(), encoded_claims.as_str()].join("."); |
| 51 | let signature = sign(message.as_bytes(), key, header.alg)?; |
| 52 | |
| 53 | Ok(Jws { |
| 54 | protected: encoded_header, |
| 55 | payload: encoded_claims, |
| 56 | signature, |
| 57 | _pd: Default::default(), |
| 58 | }) |
| 59 | } |
| 60 | |
| 61 | /// Validate a received JWS and decode into the header and claims. |
| 62 | pub fn decode<T: DeserializeOwned>( |