#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

#446 in Encoding

Download history 348/week @ 2024-12-05 366/week @ 2024-12-12 283/week @ 2024-12-19 197/week @ 2024-12-26 512/week @ 2025-01-02 342/week @ 2025-01-09 383/week @ 2025-01-16 333/week @ 2025-01-23 356/week @ 2025-01-30 380/week @ 2025-02-06 576/week @ 2025-02-13 267/week @ 2025-02-20 220/week @ 2025-02-27 2456/week @ 2025-03-06 3626/week @ 2025-03-13 3338/week @ 2025-03-20

9,641 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
~265K SLoC