#jwk #jwt

jwks

A library for retrieving and parsing JSON Web Key Sets (JWKS)

5 releases (3 breaking)

0.4.0 Feb 27, 2025
0.3.0 Feb 14, 2025
0.2.0 Jan 5, 2025
0.1.3 Feb 12, 2024
0.1.2 Jan 26, 2024

#345 in Authentication

Download history 398/week @ 2025-02-02 453/week @ 2025-02-09 478/week @ 2025-02-16 245/week @ 2025-02-23 888/week @ 2025-03-02 3038/week @ 2025-03-09 4050/week @ 2025-03-16 4462/week @ 2025-03-23 5015/week @ 2025-03-30 8270/week @ 2025-04-06 9147/week @ 2025-04-13 4339/week @ 2025-04-20 6081/week @ 2025-04-27 4132/week @ 2025-05-04 2808/week @ 2025-05-11 1033/week @ 2025-05-18

14,291 downloads per month

MIT license

21KB
308 lines

jwks

Fetch and parse JSON Web Key Set (JWKS)

cargo add jwks

https://crates.io/crates/jwks

Usage

From a jwks url.

let jwks_url = "https://www.googleapis.com/oauth2/v3/certs";
let jwks = Jwks::from_jwks_url(jwks_url).await.unwrap();

From a openid config url.

let openid_config_url = "https://accounts.google.com/.well-known/openid-configuration";
let jwks = Jwks::from_oidc_url(openid_config_url).await.unwrap();

Use with jsonwebtokn to validate a jwt.

use jsonwebtoken::{decode, decode_header, TokenData, Validation};
use jwks::Jwks;
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Claims {
    pub sub: String,
}

#[tokio::main]
async fn main() {
    let jwt = "...base64-encoded-jwt...";

    // get the kid from jwt
    let header = decode_header(jwt).expect("jwt header should be decoded");
    let kid = header.kid.as_ref().expect("jwt header should have a kid");

    // get a jwk from jwks by kid
    let jwks_url = "https://www.googleapis.com/oauth2/v3/certs";
    let jwks = Jwks::from_jwks_url(jwks_url).await.unwrap();
    let jwk = jwks.keys.get(kid).expect("jwt refer to a unknown key id");

    let validation = Validation::default();
    let decoded_token: TokenData<Claims> =
        decode::<Claims>(jwt, &jwk.decoding_key, &validation).expect("jwt should be valid");
}

Dependencies

~7–19MB
~257K SLoC