From 53b223bc32ce29ffb1f2a9b69f4af07812654b4e Mon Sep 17 00:00:00 2001 From: tottoto Date: Wed, 1 Oct 2025 12:11:13 +0900 Subject: [PATCH] Implement TryFrom &Jwk for DecodingKey --- examples/auth0.rs | 6 ++---- src/decoding.rs | 8 ++++++++ 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/examples/auth0.rs b/examples/auth0.rs index f3857222..ca9714f5 100644 --- a/examples/auth0.rs +++ b/examples/auth0.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use jsonwebtoken::jwk::JwkSet; -use jsonwebtoken::{DecodingKey, Validation, decode, decode_header}; +use jsonwebtoken::{Validation, decode, decode_header}; const TOKEN: &str = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjFaNTdkX2k3VEU2S1RZNTdwS3pEeSJ9.eyJpc3MiOiJodHRwczovL2Rldi1kdXp5YXlrNC5ldS5hdXRoMC5jb20vIiwic3ViIjoiNDNxbW44c281R3VFU0U1N0Fkb3BhN09jYTZXeVNidmRAY2xpZW50cyIsImF1ZCI6Imh0dHBzOi8vZGV2LWR1enlheWs0LmV1LmF1dGgwLmNvbS9hcGkvdjIvIiwiaWF0IjoxNjIzNTg1MzAxLCJleHAiOjE2MjM2NzE3MDEsImF6cCI6IjQzcW1uOHNvNUd1RVNFNTdBZG9wYTdPY2E2V3lTYnZkIiwic2NvcGUiOiJyZWFkOnVzZXJzIiwiZ3R5IjoiY2xpZW50LWNyZWRlbnRpYWxzIn0.0MpewU1GgvRqn4F8fK_-Eu70cUgWA5JJrdbJhkCPCxXP-8WwfI-qx1ZQg2a7nbjXICYAEl-Z6z4opgy-H5fn35wGP0wywDqZpqL35IPqx6d0wRvpPMjJM75zVXuIjk7cEhDr2kaf1LOY9auWUwGzPiDB_wM-R0uvUMeRPMfrHaVN73xhAuQWVjCRBHvNscYS5-i6qBQKDMsql87dwR72DgHzMlaC8NnaGREBC-xiSamesqhKPVyGzSkFSaF3ZKpGrSDapqmHkNW9RDBE3GQ9OHM33vzUdVKOjU1g9Leb9PDt0o1U4p3NQoGJPShQ6zgWSUEaqvUZTfkbpD_DoYDRxA"; const JWKS_REPLY: &str = r#" @@ -21,8 +21,6 @@ fn main() -> Result<(), Box> { return Err("No matching JWK found for the given kid".into()); }; - let decoding_key = DecodingKey::from_jwk(jwk)?; - let validation = { let mut validation = Validation::new(header.alg); validation.set_audience(&["https://dev-duzyayk4.eu.auth0.com/api/v2/"]); @@ -31,7 +29,7 @@ fn main() -> Result<(), Box> { }; let decoded_token = - decode::>(TOKEN, &decoding_key, &validation)?; + decode::>(TOKEN, &jwk.try_into()?, &validation)?; println!("{:#?}", decoded_token); diff --git a/src/decoding.rs b/src/decoding.rs index 8d9a72f9..5fc70b8e 100644 --- a/src/decoding.rs +++ b/src/decoding.rs @@ -251,6 +251,14 @@ impl DecodingKey { } } +impl TryFrom<&Jwk> for DecodingKey { + type Error = crate::errors::Error; + + fn try_from(jwk: &Jwk) -> Result { + Self::from_jwk(jwk) + } +} + /// Decode and validate a JWT /// /// If the token or its signature is invalid or the claims fail validation, it will return an error.