RemoteJwksDecoder

Struct RemoteJwksDecoder 

Source
pub struct RemoteJwksDecoder { /* private fields */ }
Expand description

JWT decoder that fetches and caches keys from a remote JWKS endpoint.

Automatically fetches JWKS from the specified URL, caches keys by their kid (key ID), and periodically refreshes them in the background. Includes retry logic for robustness.

§Example

use axum_jwt_auth::RemoteJwksDecoder;
use jsonwebtoken::{Algorithm, Validation};

let decoder = RemoteJwksDecoder::builder()
    .jwks_url("https://example.com/.well-known/jwks.json".to_string())
    .validation(Validation::new(Algorithm::RS256))
    .build()
    .unwrap();

// Initialize: fetch keys and start background refresh task
decoder.initialize().await.unwrap();

Implementations§

Source§

impl RemoteJwksDecoder

Source

pub fn new(jwks_url: String) -> Result<Self, Error>

Creates a new RemoteJwksDecoder with the given JWKS URL and default settings.

§Errors

Returns Error::Configuration if the builder fails to construct the decoder.

Source

pub fn builder() -> RemoteJwksDecoderBuilder

Creates a new builder for configuring a remote JWKS decoder.

Source

pub async fn initialize(&self) -> Result<CancellationToken, Error>

Performs an initial fetch of JWKS keys and starts the background refresh task.

This method should be called once after construction. It will:

  1. Immediately fetch keys from the JWKS endpoint
  2. Spawn a background task to periodically refresh keys

Returns a CancellationToken that can be used to gracefully stop the background refresh task.

§Errors

Returns an error if the initial fetch fails after all retry attempts.

§Example
let decoder = RemoteJwksDecoder::builder()
    .jwks_url("https://example.com/.well-known/jwks.json".to_string())
    .validation(Validation::new(Algorithm::RS256))
    .build()?;

// Fetch keys and start background refresh
let shutdown_token = decoder.initialize().await?;

// Later, during application shutdown:
shutdown_token.cancel();
Source

pub async fn refresh(&self) -> Result<(), Error>

Manually triggers a JWKS refresh with retry logic.

Useful for forcing an update outside the normal refresh cycle.

§Errors

Returns an error if the refresh fails after all retry attempts.

Source

pub async fn refresh_keys_periodically(&self, shutdown_token: CancellationToken)

Runs a loop that periodically refreshes the JWKS cache until cancelled.

This method should be spawned in a background task using tokio::spawn. Refresh failures are logged, and the decoder continues using stale keys until the next successful refresh.

The loop will exit gracefully when the shutdown_token is cancelled.

§Example
use tokio_util::sync::CancellationToken;

let decoder = RemoteJwksDecoder::builder()
    .jwks_url("https://example.com/.well-known/jwks.json".to_string())
    .build()
    .unwrap();

let shutdown_token = CancellationToken::new();
let decoder_clone = decoder.clone();
let token_clone = shutdown_token.clone();

tokio::spawn(async move {
    decoder_clone.refresh_keys_periodically(token_clone).await;
});

// Later, to stop the refresh task:
shutdown_token.cancel();

Trait Implementations§

Source§

impl Clone for RemoteJwksDecoder

Source§

fn clone(&self) -> RemoteJwksDecoder

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T> JwtDecoder<T> for RemoteJwksDecoder
where T: for<'de> DeserializeOwned,

Source§

fn decode<'a>( &'a self, token: &'a str, ) -> Pin<Box<dyn Future<Output = Result<TokenData<T>, Error>> + Send + 'a>>

Decodes and validates a JWT token string, returning the parsed claims. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,