Struct KeySet

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

Abstracts a remote Amazon Cognito JWKS key set

The key set represents the public key information for one or more RSA keys that Amazon Cognito uses to sign tokens. To verify a token from Cognito the token’s kid is used to look up the corresponding public key from this set which can be used to verify the token’s signature.

Building on top of the Verifier API from jsonwebtokens, a KeySet provides some helpers for building a Verifier for Cognito Access token claims or ID token claims - referencing the region and pool details used to construct the keyset.

Example:

let keyset = KeySet::new("eu-west-1", "my-user-pool-id")?;
let verifier = keyset.new_id_token_verifier(&["client-id-0", "client-id-1"])
    .string_equals("custom_claim0", "value")
    .string_equals("custom_claim1", "value")
    .build()?;
let claims = keyset.verify(token, &verifier).await?;

Internally a KeySet holds a cache of Algorithm structs (see the jsonwebtokens API for further details) where each Algorithm represents one RSA public key.

Although keyset.verify() can be very convenient, if you need to avoid network I/O when verifying tokens it’s also possible to prefetch the remote JWKS key set ahead of time and try_verify() can be used to verify a token without any network I/O. This can be useful if you don’t have an async context when verifying tokens.

let keyset = KeySet::new("eu-west-1", "my-user-pool-id")?;
keyset.prefetch_jwks().await?;
let verifier = keyset.new_id_token_verifier(&["client-id-0", "client-id-1"])
    .string_equals("custom_claim0", "value")
    .string_equals("custom_claim1", "value")
    .build()?;
let claims = keyset.try_verify(token, &verifier)?;

It’s also possible to perform cache lookups directly to access an Algorithm if you need to use the jsonwebtokens API directly:

let keyset = KeySet::new("eu-west-1", "my-user-pool-id")?;
keyset.prefetch_jwks().await?;

let verifier = keyset.new_id_token_verifier(&["client-id-0", "client-id-1"])
    .string_equals("custom_claim0", "value")
    .string_equals("custom_claim1", "value")
    .build()?;

let header = jwt::raw::decode_header_only(token)?;
if let Some(Value::String(kid)) = header.get("kid") {
    let alg = keyset.try_cache_lookup_algorithm(kid)?;
    let claims = verifier.verify(token, &alg)?;

    // Whoop!
} else {
    Err(jwt::error::Error::MalformedToken(jwt::error::ErrorDetails::new("Missing kid")))?;
};

Implementations§

Source§

impl KeySet

Source

pub fn new( region: impl Into<String>, pool_id: impl Into<String>, ) -> Result<Self, Error>

Constructs a key set that corresponds to a remote Json Web Key Set published by Amazon for a given region and Cognito User Pool ID.

Source

pub fn new_id_token_verifier(&self, client_ids: &[&str]) -> VerifierBuilder

Returns a VerifierBuilder that has been pre-configured to validate an AWS Cognito ID token. This can be further configured for verifying other custom claims before calling .build() to create a Verifier

Source

pub fn set_min_jwks_fetch_interval(&mut self, interval: Duration)

Set’s the minimum time between attempts to fetch the remote JWKS key set

By default this is one minute, to throttle requests in case there is a transient network problem

Source

pub fn min_jwks_fetch_interval(&mut self) -> Duration

Get’s the minimum time between attempts to fetch the remote JWKS key set

Source

pub fn new_access_token_verifier(&self, client_ids: &[&str]) -> VerifierBuilder

Returns a VerifierBuilder that has been pre-configured to validate an AWS Cognito access token. This can be further configured for verifying other custom claims before calling .build() to create a Verifier

Source

pub fn try_cache_lookup_algorithm( &self, kid: &str, ) -> Result<Arc<Algorithm>, Error>

Looks for a cached Algorithm based on the given JWT token’s key ID (‘kid’)

This is a lower-level API in case you need to use the jsonwebtokens Algorithm API directly.

Returns an Arc<Algorithm> corresponding to the give key ID (kid) or returns a CacheMiss error if the Algorithm / key is not cached.

Source

pub async fn verify( &self, token: &str, verifier: &Verifier, ) -> Result<Value, Error>

Verify a token’s signature and its claims

Source

pub async fn verify_for_time( &self, token: &str, verifier: &Verifier, time_now: u64, ) -> Result<TokenData, Error>

Verify a token’s signature and its claims, given a specific unix epoch timestamp

Source

pub fn try_verify( &self, token: &str, verifier: &Verifier, ) -> Result<Value, Error>

Try and verify a token’s signature and claims without performing any network I/O

To be able to verify a token in a synchronous context (but without blocking) this API lets you try and verify a token, and if the required Algorithm / key has not been cached yet then it will return a CacheMiss error.

Source

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

Ensure the remote Json Web Key Set is downloaded and cached

Trait Implementations§

Source§

impl Clone for KeySet

Source§

fn clone(&self) -> KeySet

Returns a copy 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 Debug for KeySet

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for KeySet

§

impl RefUnwindSafe for KeySet

§

impl Send for KeySet

§

impl Sync for KeySet

§

impl Unpin for KeySet

§

impl UnwindSafe for KeySet

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> 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> 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<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<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T