#cognito #token #jwk #jwks

jsonwebtokens-cognito

Decodes and verifies Json Web Tokens issued by AWS Cognito

9 releases

0.1.1 May 8, 2022
0.1.0-alpha.10 Aug 15, 2021
0.1.0-alpha.9 Jan 17, 2020
0.1.0-alpha.8 Dec 30, 2019

#460 in Authentication

Download history 264/week @ 2024-07-20 466/week @ 2024-07-27 238/week @ 2024-08-03 342/week @ 2024-08-10 408/week @ 2024-08-17 293/week @ 2024-08-24 401/week @ 2024-08-31 434/week @ 2024-09-07 552/week @ 2024-09-14 589/week @ 2024-09-21 446/week @ 2024-09-28 540/week @ 2024-10-05 374/week @ 2024-10-12 372/week @ 2024-10-19 339/week @ 2024-10-26 370/week @ 2024-11-02

1,524 downloads per month
Used in actix-web-middleware-cogn…

MIT license

21KB
253 lines

A Rust library for verifying Json Web Tokens issued by AWS Cognito

Install

jsonwebtokens-cognito = "0.1.0-alpha"

Usage

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?;

This library builds on top of jsonwebtokens token verifiers.

The keyset will fetch from the appropriate .jwks url when verifying the first token or, alternatively the cache can be primed by calling keyset.prefetch_jwks():

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

If you need to perform token verification in a non-async context, or don't wan't to allow network I/O while verifying tokens then if you have explicitly prefetched the jwks key set you can verify tokens with try_verify:

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).await?;

try_verify() will return a CacheMiss error if the required key has not been prefetched

A Keyset is Send safe so it can be used for authentication within a multi-threaded server.

Examples:

Verify an AWS Cognito Access token

let keyset = KeySet::new(AWS_REGION, AWS_POOL_ID)?;
let verifier = keyset.new_access_token_verifier(&[AWS_CLIENT_ID]).build()?;

keyset.verify(&token_str, &verifier).await?;

Verify an AWS Cognito Identity token

let keyset = KeySet::new(AWS_REGION, AWS_POOL_ID)?;
let verifier = keyset.new_id_token_verifier(&[AWS_CLIENT_ID]).build()?;

keyset.verify(&token_str, &verifier).await?;

Verify an AWS Cognito Access token with custom claims

let keyset = KeySet::new(AWS_REGION, AWS_POOL_ID)?;
let verifier = keyset.new_access_token_verifier(&[AWS_CLIENT_ID])
    .string_equals("my_claim", "foo")
    .build()?;

keyset.verify(&token_str, &verifier).await?;

See jsonwebtokens for more examples of how to verify custom claims.

Dependencies

~11–27MB
~448K SLoC