Skip to main content

axum_jwt_bridge/
lib.rs

1//! # axum-jwt-bridge
2//!
3//! JWT encode/decode for [Axum](https://docs.rs/axum) microservices,
4//! compatible with Laravel's `tymon/jwt-auth` and any HS256 JWT issuer.
5//!
6//! Extracts `user_id: u32` from the `sub` claim.  Role-based
7//! authorization is the consuming application's responsibility.
8//!
9//! ## Usage
10//!
11//! ```rust,no_run
12//! use axum::{routing::get, Extension, Router};
13//! use axum_jwt_bridge::{AuthUser, JwtConfig};
14//!
15//! async fn handler(user: AuthUser) -> String {
16//!     format!("user_id = {}", user.user_id)
17//! }
18//!
19//! #[tokio::main]
20//! async fn main() {
21//!     // Ensure JWT_SECRET (and optionally BASE_URL, AUTH_PATH,
22//!     // USER_MODEL_PATH) are set in the environment before calling from_env.
23//!     let config = JwtConfig::from_env().unwrap();
24//!
25//!     let app: Router = Router::new()
26//!         .route("/me", get(handler))
27//!         .layer(Extension(config));
28//!
29//!     let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
30//!     axum::serve(listener, app).await.unwrap();
31//! }
32//! ```
33//!
34//! ## Custom extra claims
35//!
36//! ```rust
37//! use serde::{Deserialize, Serialize};
38//! use axum_jwt_bridge::{Claims, verify_jwt_as, generate_jwt_with, JwtConfig};
39//!
40//! #[derive(Debug, Clone, Serialize, Deserialize)]
41//! struct MyExtra {
42//!     #[serde(default)]
43//!     tenant_id: Option<String>,
44//! }
45//!
46//! # fn example() {
47//! let config = JwtConfig::new("secret");
48//! let token = generate_jwt_with(42, &config, MyExtra { tenant_id: Some("acme".into()) }).unwrap();
49//! let claims: Claims<MyExtra> = verify_jwt_as(&token, &config).unwrap();
50//! assert_eq!(claims.extra.tenant_id.as_deref(), Some("acme"));
51//! # }
52//! ```
53//!
54//! ## Environment variables (`JwtConfig::from_env`)
55//!
56//! This Mod does **not** load `.env` files.
57//!
58//! | Variable               | Required | Default                 | Notes                                     |
59//! |------------------------|----------|-------------------------|-------------------------------------------|
60//! | `JWT_SECRET`           | one of   | —                       | HS256 shared secret                       |
61//! | `JWT_KEY_NAME`         | these    | —                       | EdDSA: SSH-convention key name — `~/.ssh/{name}` / `~/.ssh/{name}.pub` |
62//! | `JWT_KEY_PATH`         | three    | —                       | EdDSA: exact PEM file path, used as-is    |
63//! | `BASE_URL`             | no       | *(unset — no `iss` claim)* | Combined with `AUTH_PATH` to form `iss` |
64//! | `AUTH_PATH`            | no       | `/api/login`            | Only used if `BASE_URL` is set            |
65//! | `JWT_TTL_DAYS`         | no       | `14`                    | Token lifetime in days                    |
66//! | `USER_MODEL_PATH`      | no       | *(unset — no prv)*      | Sets `prv` claim and **enables** its check|
67//! | `JWT_VALIDATE_ISSUER`  | no       | `false`                 | `true` or `1` to enable                  |
68//! | `JWT_AUDIENCE`         | no       | *(unset)*               | Comma-separated audience URIs             |
69//!
70//! For `JWT_KEY_NAME` / `JWT_KEY_PATH`, the PEM itself isn't read here —
71//! it's read from disk lazily, at sign/verify time. See
72//! [`AuthType::PubPriKey`] / [`AuthType::PubPriPath`] for details.
73//!
74//! ## Laravel migration
75//!
76//! To validate tokens still being issued by a Laravel `tymon/jwt-auth` server,
77//! share the same `JWT_SECRET` and set `USER_MODEL_PATH` (which auto-enables
78//! `prv` validation):
79//!
80//! ```rust,no_run
81//! use axum_jwt_bridge::JwtConfig;
82//!
83//! // Code-based setup:
84//! let config = JwtConfig::laravel_compat("your-jwt-secret", "App\\Models\\User");
85//!
86//! // Or via environment (JWT_SECRET + USER_MODEL_PATH):
87//! let config = JwtConfig::from_env().unwrap();
88//! ```
89//!
90//! When your Rust services start issuing tokens too, the same config signs them
91//! with the same `prv` hash, so Laravel can validate them without any changes.
92
93pub mod claims;
94pub mod config;
95pub mod error;
96pub mod middleware;
97pub mod token;
98
99pub use claims::{Claims, NoExtraClaims};
100pub use config::{AuthType, JwtConfig, MultiJwtConfig, ProviderStrategy};
101pub use error::AuthError;
102pub use middleware::{AuthUser, OptionalAuthUser};
103pub use token::{
104    generate_jti, generate_jwt, generate_jwt_with,
105    verify_jwt, verify_jwt_as,
106    verify_jwt_any, verify_jwt_any_as,
107};