auth0_jwt/lib.rs
1//! Copyright (C) 2022 Federico Vitale
2//!
3//! Implements a library to iteract and decode JWTs
4//! generated from auth0
5//!
6//! ## Usage Example (via Axum)
7//! > with `axum` and `claims` features enabled
8//!
9//!
10//! ```no_run
11//! #[cfg(all(feature = "claims", feature = "claims"))]
12//! use auth0_jwt::claims::Claims;
13//! #[cfg(all(feature = "claims", feature = "claims"))]
14//! use axum::response::IntoResponse;
15//!
16//! struct ClaimsContent {
17//! exp: usize,
18//! iat: usize,
19//! }
20//!
21//! // Using the `Claims` struct lets you decode automatically the value into a struct.
22//! #[cfg(all(feature = "claims", feature = "claims"))]
23//! async fn handler(Claims(claims): Claims<ClaimsContent>) -> impl IntoResponse {
24//! // your claims
25//! println!("Exp: {}, Iat: {}", claims.exp, claims.iat);
26//! }
27//! ```
28
29use alcoholic_jwt::{token_kid, validate};
30pub use alcoholic_jwt::{Validation, JWKS};
31
32pub mod error;
33
34/// Includes feature flagged adapters for various
35/// http servers such as `axum`, `actix-web`, `rocket` etc
36pub mod http;
37
38#[cfg(feature = "claims")]
39pub mod claims;
40
41mod util;
42
43use crate::error::{Error, Result};
44
45/// Configuration for the JWT params
46pub struct Config {
47 pub issuer: String,
48 pub validations: Vec<Validation>,
49}
50
51impl Config {
52 /// Initialize the `Config` with issuer and default validations.
53 /// Default validations are: NotExpired, Issuer
54 pub fn new(issuer: &str) -> Self {
55 Self {
56 issuer: issuer.to_string(),
57 validations: vec![
58 Validation::Issuer(issuer.to_string()),
59 Validation::NotExpired,
60 ],
61 }
62 }
63}
64
65/// Returns the claims stored into the given JWT
66pub async fn get_claims(token: &str, config: Config) -> Result<serde_json::Value> {
67 let jwks = util::fetch_jwks(&config.issuer).await?;
68 let kid = token_kid(token)
69 .map_err(Error::ValidationError)?
70 .expect("Failed to decode token kid");
71
72 let jwk = jwks.find(&kid).expect("Specified key not found in set");
73
74 // validate or throw error
75 let res = validate(token, jwk, config.validations).map_err(Error::ValidationError)?;
76
77 Ok(res.claims)
78}