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,
)
| 268 | /// let token_message = decode::<Claims>(&token, &DecodingKey::from_secret("secret".as_ref()), &Validation::new(Algorithm::HS256)); |
| 269 | /// ``` |
| 270 | pub fn decode<T: DeserializeOwned>( |
| 271 | token: impl AsRef<[u8]>, |
| 272 | key: &DecodingKey, |
| 273 | validation: &Validation, |
| 274 | ) -> Result<TokenData<T>> { |
| 275 | let token = token.as_ref(); |
| 276 | let header = decode_header(token)?; |
| 277 | |
| 278 | if !validation.algorithms.contains(&header.alg) { |
| 279 | return Err(new_error(ErrorKind::InvalidAlgorithm)); |
| 280 | } |
| 281 | |
| 282 | let verifying_provider = (CryptoProvider::get_default().verifier_factory)(&header.alg, key)?; |
| 283 | |
| 284 | let (header, claims) = verify_signature(token, validation, verifying_provider)?; |
| 285 | |
| 286 | let decoded_claims = DecodedJwtPartClaims::from_jwt_part_claims(claims)?; |
| 287 | let claims = decoded_claims.deserialize()?; |
| 288 | validate(decoded_claims.deserialize()?, validation)?; |
| 289 | |
| 290 | Ok(TokenData { header, claims }) |
| 291 | } |
| 292 | |
| 293 | /// Decode a JWT with NO VALIDATION |
| 294 | /// |
nothing calls this directly
no test coverage detected