Decode and validate a JWT If the token or its signature is invalid or the claims fail validation, it will return an error. ```rust use serde::{Deserialize, Serialize}; use jsonwebtoken::{decode, DecodingKey, Validation, Algorithm}; #[derive(Debug, Clone, Serialize, Deserialize)] struct Claims { sub: String, company: String } let token = "a.jwt.token".to_string(); // Claims is a struct that imp
(
token: impl AsRef<[u8]>,
key: &DecodingKey,
validation: &Validation,
)
| 277 | /// let token_message = decode::<Claims>(&token, &DecodingKey::from_secret("secret".as_ref()).unwrap(), &Validation::new(Algorithm::HS256)); |
| 278 | /// ``` |
| 279 | pub fn decode<T: DeserializeOwned>( |
| 280 | token: impl AsRef<[u8]>, |
| 281 | key: &DecodingKey, |
| 282 | validation: &Validation, |
| 283 | ) -> Result<TokenData<T>> { |
| 284 | let token = token.as_ref(); |
| 285 | let (signature, message) = expect_two!(token.rsplitn(2, |b| *b == b'.')); |
| 286 | let (payload, header) = expect_two!(message.rsplitn(2, |b| *b == b'.')); |
| 287 | let header = Header::from_encoded(header)?; |
| 288 | |
| 289 | if !validation.algorithms.contains(&header.alg) { |
| 290 | return Err(new_error(ErrorKind::InvalidAlgorithm)); |
| 291 | } |
| 292 | |
| 293 | let verifying_provider = (CryptoProvider::get_default().verifier_factory)(&header.alg, key)?; |
| 294 | |
| 295 | verify_signature_body(message, signature, &header, validation, verifying_provider)?; |
| 296 | |
| 297 | let decoded_claims = DecodedJwtPartClaims::from_jwt_part_claims(payload)?; |
| 298 | let claims = decoded_claims.deserialize()?; |
| 299 | validate(decoded_claims.deserialize()?, validation)?; |
| 300 | |
| 301 | Ok(TokenData { header, claims }) |
| 302 | } |
| 303 | |
| 304 | /// Decode a JWT with NO VALIDATION |
| 305 | /// |
nothing calls this directly
no test coverage detected